iOS:如何在应用程序完全关闭并重新打开时获取所有推送通知userinfo?

时间:2014-06-27 21:09:39

标签: ios objective-c push-notification apple-push-notifications

我不确定这是否可行,但我需要在用户打开应用程序时获取所有推送通知userinfo。我可以在应用程序打开时或后台获取所有推送通知userinfo,但不能在应用程序完全关闭时获取。有什么方法吗?下面的代码是我当前获取userInfo的方式。

     - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
  {

    id data = [userInfo objectForKey:@"data"];

       NSLog(@"data%@",data);

   }

4 个答案:

答案 0 :(得分:1)

您正在实施的方法无法处理这两种情况。请参阅"Local and Push Notification Programming Guide"

  

如果您的应用位于最前端,则会在其应用委托上调用application:didReceiveRemoteNotification:application:didReceiveLocalNotification:方法。如果您的应用不是最前面的或没有运行,您可以通过检查传递给您的应用代表的application:didFinishLaunchingWithOptions:的选项字典来处理通知...

答案 1 :(得分:1)

不幸的是,使用该方法的客户端目前无法查询应用程序完全关闭时发生的旧通知。请参阅此问题:didReceiveRemoteNotification when in background

解决方法是跟踪每个用户从服务器发送的通知。调用didReceiveRemoteNotification:时,您可以接收该通知并将其与当前用户的服务器消息进行比较。如果其中一个匹配,请在服务器上以某种方式标记。这样,如果在您的应用程序背景化时发送了消息,您可以查询尚未从服务器标记的消息并获取所有“遗漏”通知。

答案 2 :(得分:0)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
//Notifications
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(userInfo){
        //open from notification message
    }
return YES;
}

答案 3 :(得分:0)

您可以将此代码添加到AppDelegate的applicationWillEnterForeground方法中:

-(void)applicationWillEnterForeground:(UIApplication *)application {

    // this method is called when staring an app that was closed / killed / never run before (after applicationDidFinishLaunchingWithOptions) and every time the app is reopened or change status from background to foreground (ex. returning from a mobile call or after the user switched to other app and then came back)

    [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
        NSLog(@"AppDelegate-getDeliveredNotificationsWithCompletionHandler there were %lu notifications in notification center", (unsigned long)[notifications count]); 

        for (UNNotification* notification in notifications) {

            NSDictionary *userInfo = notification.request.content.userInfo;
            if (userInfo) {
                NSLog(@"Processed a notification in getDeliveredNotificationsWithCompletionHandler, with this info: %@", userInfo);
                [self showPushNotificationInAlertController:userInfo]; // this is my method to display the notification in an UIAlertController
            }
        }
        UIApplication.sharedApplication.applicationIconBadgeNumber = 0;

    }];
} 
}

从方法应用程序didFinishLaunchingWithOptions中删除此行:如果已将其包括在其中,因为它会清除徽章编号以及通知中心中的所有通知:

UIApplication.sharedApplication.applicationIconBadgeNumber = 0;

该软件当前在iOS 12中运行,没有机会在早期版本中进行测试。