我已經找到了解決辦法,這裏是代碼:
- (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的我用來存放所有的全局變量,它採用國際志願者組織,當值的變化,它會在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";
}
最後感謝所有答案提供者。
即使您使用了didReceiveRemoteNotification:fetchCompletionHandler,您仍然需要用戶點擊通知才能調用該方法。 –