iOS10推送通知適配

weixin_33866037發表於2017-04-24

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

2,註冊通知

#defineIOS8 ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 9.0)#defineIOS8_10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 10.0)#defineIOS10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中

3038868-bfb162685927daaa.gif

if(IOS10) {        UNUserNotificationCenter *center =[UNUserNotificationCenter currentNotificationCenter];        center.delegate =self;        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError *_Nullable error) {if (!error) {                NSLog(@"succeeded!");            }        }];    }elseif(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];

}

3038868-48a8811925676fd5.gif

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

相關文章