如果应用程序已经在后台运行,当用户点击通知时,如何获得推送通知的有效载荷?

如果向用户显示推送通知,并且用户点击它并且应用从后台状态进入前台,那么应用如何获得通知的有效载荷

由于该应用程序已在运行didFinishLaunchingWithOptions :将不会被调用,并且因为该应用程序在推送到达时didReceiveRemoteNotification :将不会被调用。

有两个地方,所以我通常做一个方法来处理这样的事情:

 - (void)handleMessageFromRemoteNotification:(NSDictionary *)userInfo 

然后在: application:didFinishLaunchingWithOptions:

 if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]) { [self handleMessageFromRemoteNotification:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]]; } 

还在: application:didReceiveRemoteNotification: [self handleMessageFromRemoteNotification:userInfo

如果你想做一些不同的,如果应用程序正在运行检查application.applicationState == UIApplicationStateActive didReceiveRemoteNotification

根据苹果文档,当用户点击通知的动作button时,会调用didFinishLauchingWithOptions:方法。

作为提示通知的结果,用户点击警报的动作button或点击(或点击)应用程序图标。 如果点击操作button(在运行iOS的设备上),系统启动应用程序,应用程序调用其代理的应用程序:didFinishLaunchingWithOptions:方法(如果已实施); 它传入通知负载(用于远程通知)或本地通知对象(用于本地通知)。

然后在这个方法中很容易恢复通知的内容,例如:

 UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if (localNotif) { NSString *itemName = [localNotif.userInfo objectForKey:ToDoItemKey]; [viewController displayItem:itemName]; // custom method app.applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber-1; } 

“因为这个应用程序在推送到达didReceiveRemoteNotification:时不会被调用。”

这个或者didReceiveRemoteNotification:withExpirationHandler应该在应用程序在后台被调用,并且在用户点击通知时切换到前台。

然而,当我不明白这个原因是因为推送的内容不正确时,我陷入了一种情况,我不记得细节,但仔细检查了那里的内容。