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

时间:2016-06-20 04:29:48

标签: ios objective-c ios8 push-notification

我已经搜索了2天的答案,仍然没有得到答案。 要求是我们的服务器用一些数据向我的APP发送APNS,我应该将数据改为userDefaults以供进一步使用。

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

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

2 个答案:

答案 0 :(得分:0)

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

  • 我们创建了一个API
  • 每当您的应用进入前台时都会调用
  • 然后它将检查特定通知是READ还是UNREAD,然后关于该响应,我更改了NSUserDefaults
  • 的标志

我们可以有多种方案来处理这种情况。

答案 1 :(得分:0)

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

- (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";
}

最后感谢所有答案提供者。