我已经搜索了两天的答案,但仍然没有得到答案。我们的要求是我们的服务器向我的应用程序发送一个带有一些数据的APNS,我应该将这些数据正确地输入到userDefaults中以供进一步使用。
到目前为止,我所做的就是让didReceiveRemoteNotification发挥作用。这意味着当应用程序处于后台时,只有当用户点击警报时,我才能完成保存过程。
我试着用didReceiveRemoteNotification:fetchCompletionHandler.但我真的搞不懂它是怎么工作的。代表从来没被叫过吗?我读了苹果开发人员的文档,仍然没有帮助。谁能给我一个示例代码吗?特别是告诉我APNS的内容应该是。非常感谢
发布于 2016-06-20 07:32:32
我找到了解决方案,下面是代码:
- (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";
}最后,感谢所有的答案提供者。
发布于 2016-06-20 05:34:59
当应用程序处于后台时,您不能使用推送通知进行任何操作。当用户点击它时,您可以做进一步的操作。我也面临着同样的问题,但我必须考虑到API,我们所做的。
NSUserDefaults的标志。我们可以有多个场景来处理这种情况。
https://stackoverflow.com/questions/37914643
复制相似问题