iOS10正式版發布之後,網上各種適配XCode8以及iOS10的文章滿天飛。但對於iOS10適配遠程推送的文章卻不多。iOS10對於推送的修改還是非常大的,新增了UserNotifications Framework,今天就結合自己的項目,說一說實際適配的情況。
一、Capabilities中打開Push Notifications 開關
在XCode7中這裡的開關不打卡,推送也是可以正常使用的,但是在XCode8中,這裡的開關必須要打開,不然會報錯:
Error Domain=NSCocoaErrorDomain Code=3000 "未找到應用程序的“aps-environment”的授權字符串" UserInfo={NSLocalizedDescription=未找到應用程序的“aps-environment”的授權字符串}
打開後會生成entitlements文件,在這裡可以設置APS Environment
二、推送的注冊
首先引入UserNotifications Framework,
import <UserNotifications/UserNotifications.h>
iOS10修改了注冊推送的方法,這裡我們又要對不同版本分別進行設置了。在application didFinishLaunchingWithOptions方法中修改以前的推送設置(我只實現了iOS8以上的設置)
if (IOS_VERSION >= 10.0) { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { DLog(@"request authorization succeeded!"); } }]; } else { if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) { //IOS8,創建UIUserNotificationSettings,並設置消息的顯示類類型 UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil]; [application registerUserNotificationSettings:notiSettings]; } }
三、UNUserNotificationCenterDelegate代理實現
在iOS10中處理推送消息需要實現UNUserNotificationCenterDelegate的兩個方法:
復制代碼 代碼如下:- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
其中第一個方法為App在前台的時候收到推送執行的回調方法,第二個為App在後台的時候,點擊推送信息,進入App後執行的 回調方法。
以前處理推送,信息是在userInfo參數中,而新方法中表明上看並沒有這個參數,其實我們一樣可以獲取到userInfo,如下:
/// App在前台時候回調 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { NSDictionary *userInfo = notification.request.content.userInfo; [self handleRemoteNotificationForcegroundWithUserInfo:userInfo]; } /// App在後台時候點擊推送調用 - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { NSDictionary *userInfo = response.notification.request.content.userInfo; [self handleRemoteNotificationBackgroundWithUserInfo:userInfo]; }
完成上面三個步驟的設置,對於iOS10的推送設置基本就適配了。要想自定義Notification Content或者實現其他NotificationAction請參考其他文章。這裡只是做了對iOS10的適配。
本文已被整理到了《iOS推送教程》,歡迎大家學習閱讀。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。