標籤:
iOS10推送新增了UserNotifications Framework,使用起來其實很簡單。
只是在iOS10以上系統上點擊通知欄,回調方法不再走原來的這兩個方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {}- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {}
而是在前台的時候回調
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
從後台進入的時候回調
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
直接說怎麼用吧:
1,匯入標頭檔
#import <UserNotifications/UserNotifications.h>
2,註冊通知
#define IOS8 ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 9.0)#define IOS8_10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 10.0)#define IOS10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中
if (IOS10) { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"succeeded!"); } }]; } else if (IOS8_10){//iOS8-iOS10 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil]; [application registerUserNotificationSettings:settings]; [application registerForRemoteNotifications]; } else {//iOS8以下 [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; }
3,回調方法中,擷取通知數據(前台類似不做說明)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { NSDictionary *userInfo = response.notification.request.content.userInfo; //訊息處理}
4,對於本地通知沒有什麼變化依然會回調
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
iOS10推播通知適配