如何在后台处理远程通知IOS 8?

How to handle remote notification in background IOS 8?

我找了2天的答案,还是没找到答案。 要求是我们的服务器向我的APP发送一个APNS和一些数据,我应该将这些数据正确放入userDefaults以供进一步使用。

到目前为止我所做的是使 didReceiveRemoteNotification 工作。所以这意味着当应用程序在后台时,我只能在用户点击警报时完成保存过程。

我正在尝试使用 didReceiveRemoteNotification:fetchCompletionHandler。 但我真的不知道它是如何工作的。代表永远不会被召唤? 我阅读了苹果开发者文档仍然没有帮助。请有人给我一个示例代码。并特别告诉我确切的 APNS 内容。 非常感谢

当应用程序处于后台时,您无法对推送通知执行任何操作。当用户点击它时,您可以进行进一步的操作。 我也遇到了同样的问题,但我不得不考虑 API,我们做了什么

  • 我们创建了一个 API
  • 每次您的应用进入前台时都会调用此方法
  • 然后它将检查特定通知是已读还是未读,然后针对该响应,我更改了 NSUserDefaults
  • 的标志

我们可以有多种场景来处理这种情况。

我找到了解决方案,这是代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//push notification
UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//because our sever guy only wants a string, so i send him a string without brackets
NSString * token = [[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""];
//because they only want the token to be uploaded after user login, so i save it in a variable.
VAR_MANAGER.APNSToken = token;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
NSLog(@"userInfo: %@", userInfo);
if (userInfo != nil) {
    [self updateNotificationData:userInfo];
}
completionHandler(UIBackgroundFetchResultNoData);
}

- (void)updateNotificationData: (NSDictionary *)userInfo {
NSMutableArray *notificationDataArray = [NSMutableArray arrayWithArray:VAR_MANAGER.notificationDataArray];
//the app will add the userInfo into the array silently, but when user clicked on the notification alert, the delegate will run again, so I check if the previous added entry is the same as current one.
for (int i = 0; i < notificationDataArray.count; i++) {
    if ([userInfo isEqualToDictionary:notificationDataArray[i]]) return;
}
[notificationDataArray addObject:userInfo];
VAR_MANAGER.notificationDataArray = notificationDataArray;
}

VAR_MANAGER是我用来存放所有全局变量的NSObject,它使用KVO,当值改变时,它会存放在userDefault中。

//here is the userInfo i obtained from push notification, remember the content-available = 1, that is the most important part
{
    aps =         {
        alert = success;
        badge = 1;
        "content-available" = 1;
        sound = default;
    };
    status = 1;
    "time_stamp" = "1466407030.006493";
}

最后感谢各位解答者