我已经实现了应用程序:didReceiveRemoteNotification:fetchCompletionHandler:在我的应用程序委托中来响应推送通知.
当应用程序处于后台时收到通知时,立即调用此方法,并在完成后获取新数据并执行完成块.所有文件.但是,如果我点击通知警报,此方法再次被调用,导致另一个网络调用和UI更新.我会期望这种方法每次推送通知一次,而不是一次收到并再次执行.
其他人如何实施这种方法?
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [self loadSomeResource:^(NSData *data,NSError *error){ if (error) { completionHandler(UIBackgroundFetchResultFailed); } else if (data){ completionHandler(UIBackgroundFetchResultNewData); } else { completionHandler(UIBackgroundFetchResultNoData); } }]; }
解决方法
以下是应用程序中要注意的事项:didReceiveRemoteNotification:fetchCompletionHandler:方法,当您收到推送通知:1.当应用程序未启动时(即应用程序既不在后台也不在前台),该方法被调用一次,applicationState将是UIApplicationStateInactive.2.当应用程序在前台时,applicationState将是UIApplicationStateActive.3.当应用程序在后台时,该方法被调用两次,一旦收到推送通知,以及其他时间点击该通知.当您收到推送通知时,applicationState将是UIApplicationStateBackground,当您点击该通知时,applicationState将为UIApplicationStateInactive.当applicationState将为UIApplicationStateBackground时,我们可以忽略它,因此我们可以为所有三种情况处理一次推送通知.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { if (application.applicationState == UIApplicationStateBackground) { completionHandler(UIBackgroundFetchResultNoData); return; } // Do whatever you need here and call completionHandler with appropriate UIBackgroundFetchResult }