具有后台刷新的APN。当APN交付时以及点击通知时刷新两次?

时间:2015-06-17 07:44:41

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

我正在尝试使用content-available键在我的应用中实现APN,以便触发后台刷新。这是我的代码:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{

    if([userInfo[@"aps"][@"content-available"] intValue]== 1){

        //This stops a refresh happening is a push is delivered with the app in the foreground
        if(application.applicationState!=UIApplicationStateActive){

            NSLog(@“Background push refresh called");
            [self backgroundRefreshWithPushUpdate:NO andHandler:^(BOOL successful, BOOL newMessages) {

                if(successful){


                    if(newMessages) handler(UIBackgroundFetchResultNewData);
                    else handler(UIBackgroundFetchResultNoData);


                }

                else{

                    handler(UIBackgroundFetchResultFailed);

                }


            }];



        }

        else handler(UIBackgroundFetchResultNoData);

    }


}

我有这个附加条件:if(application.applicationState!=UIApplicationStateActive)用于在后台刷新,因为如果应用在前台,我不希望它被触发。但是,如果我收到推送,然后点击通知打开应用程序,则再次调用- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler中的所有代码。这意味着当通知首次进入时会调用我的后台提取,然后在点击通知时再次调用它。我不希望这种情况发生。我有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

以下是应用程序中注意到的事项:didReceiveRemoteNotification:fetchCompletionHandler:方法,当您收到推送通知时:
1。当应用程序未启动时(即,当应用程序既不在后台也不在前台时),该方法将被调用一次, applicationState UIApplicationStateInactive 。 2。当应用程序位于前台时,该方法将被调用一次,而 applicationState 将是 UIApplicationStateActive 。当应用程序处于后台时,该方法会被调用两次,一次是在您收到推送通知时,另一次是您点击该通知时。当您收到推送通知时, 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
}