当应用程序处于后台时,您必须做几件事才能管理收到的推送通知。
首先,在您的服务器端,您必须在推送通知负载中设置{"aps":{"content-available" : 1... / $body['aps']['content-available'] =1;。
其次,在你的 Xcode 项目中,你必须适应“远程通知”。它是通过转到项目的目标 -> 能力,然后启用能力开关,并选中远程通知复选框来完成的。
第三,你必须调用application:didReceiveRemoteNotification:fetchCompletionHandler:,而不是使用didReceiveRemoteNotification,这将允许你在收到通知的那一刻在后台执行你想要的任务:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
if(application.applicationState == UIApplicationStateInactive) {
NSLog(@"Inactive - the user has tapped in the notification when app was closed or in background");
//do some tasks
[self manageRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
else if (application.applicationState == UIApplicationStateBackground) {
NSLog(@"application Background - notification has arrived when app was in background");
NSString* contentAvailable = [NSString stringWithFormat:@"%@", [[userInfo valueForKey:@"aps"] valueForKey:@"content-available"]];
if([contentAvailable isEqualToString:@"1"]) {
// do tasks
[self manageRemoteNotification:userInfo];
NSLog(@"content-available is equal to 1");
completionHandler(UIBackgroundFetchResultNewData);
}
}
else {
NSLog(@"application Active - notication has arrived while app was opened");
//Show an in-app banner
//do tasks
[self manageRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
}
最后,您必须在设置时将这种通知类型:UIRemoteNotificationTypeNewsstandContentAvailability 添加到通知设置中。
除此之外,如果您的应用在通知到达时已关闭,您必须在 didFinishLaunchingWithOptions 中进行管理,并且如果用户点击推送通知:这样做的方式是:
if (launchOptions != nil)
{
NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSLog(@"Launched from push notification: %@", dictionary);
[self manageRemoteNotification:dictionary];
}
}
当您通过点击推送通知启动应用程序时,launchOptions 为 != nil,如果您通过点击图标访问它,launchOptions 将为 == nil。
我希望它会有用。 Here it is explained by Apple.