iOS 10 消息推送(UserNotifications)祕籍總結

前言
之前說會單獨整理消息通知的內容,但是因爲工(就)作(是)的(很)事(懶)沒有更新文章,違背了自己的學習的初衷。因爲互聯網一定要有危機意識,說不定眼一睜,我們就out丟了飯碗。

圖片來源網絡.jpeg
“狼,他沒有獅子老虎強壯,也沒有大象那龐大的身軀,但至少:我從來沒在馬戲團看到過他們的身影。”

也許只有狼在一直奔跑,這是我一直喜歡它的原因,要像狼一樣不斷奔跑,才能倖存!

看完樓主裝的一手好X,我來總結一點點你都知道的通知方面的知識點!

樓主裝逼,打他.jpg
背景
iOS10 新特性一出,各個大神就早已研究新特性能給場景智能化所帶來的好處(唉,可惜我只是一個小白)。我也被安排適配iOS10的推送工作!

Apple 表示這是 iOS 有史以來最大的升級(our biggest release yet),更加智能開放的 Siri 、強化應用對 3D Touch 支持、 HomeKit 、電話攔截及全新設計的通知等等…

iOS 10 中將之前繁雜的推送通知統一成UserNotifications.framework 來集中管理和使用通知功能,還增加一些實用的功能——撤回單條通知、更新已展示通知、中途修改通知內容、在通知中顯示多媒體資源、自定義UI等功能,功能着實強大!

本文主要是針對iOS 10的消息通知做介紹,所以很多代碼沒有對iOS 10之前做添加適配。

基本原理
iOS推送分爲Local Notifications(本地推送) 和 Remote Notifications(遠程推送)(原理圖來源於網絡,如有侵權請告知,我會添加來源,我怕我賠不起)

Local Notifications(本地推送)

Local Notifications.png
App本地創建通知,加入到系統的Schedule裏,
如果觸發器條件達成時會推送相應的消息內容
Remote Notifications(遠程推送)

Remote Notifications1.jpg
圖中,Provider是指某個iPhone軟件的Push服務器,這篇文章我將使用我花了12塊大洋(心疼)買的 APNS Pusher 作爲我的推送源。

APNS 是Apple Push Notification Service(Apple Push服務器)的縮寫,是蘋果的服務器。

上圖可以分爲三個階段:

第一階段:APNS Pusher應用程序把要發送的消息、目的iPhone的標識打包,發給APNS。

第二階段:APNS在自身的已註冊Push服務的iPhone列表中,查找有相應標識的iPhone,並把消息發到iPhone。

第三階段:iPhone把發來的消息傳遞給相應的應用程序, 並且按照設定彈出Push通知。

Remote Notifications2.jpeg
從上圖我們可以看到:

首先是應用程序註冊消息推送。

IOS跟APNS Server要deviceToken。應用程序接受deviceToken。

應用程序將deviceToken發送給PUSH服務端程序。

服務端程序向APNS服務發送消息。

APNS服務將消息發送給iPhone應用程序。

基本配置和基本方法
如果只是簡單的本地推送,跳過1 2 步驟,直接到3

1、 如果你的App有遠端推送的話,那你需要開發者賬號的,需要新建一個對應你bundle的push 證書。證書這一塊我就不說了,如果針對證書有什麼問題可以給我留言,我會單獨把證書相關的知識點整理起來!當然本人是非常喜歡的分享的(又裝逼),如果你沒有賬號,我可以把我測試用的證書發給你,用於你的測試和學習,私聊我。
2、 Capabilities中打開Push Notifications 開關
在XCode7中這裏的開關不打開,推送也是可以正常使用的,但是在XCode8中,這裏的開關必須要打開,不然會報錯:

Error Domain=NSCocoaErrorDomain Code=3000 “未找到應用程序的“aps-environment”的授權字符串” UserInfo={NSLocalizedDescription=未找到應用程序的“aps-environment”的授權字符串}
打開後會自動在項目裏生成entitlements文件。

Push Notification開關.png

entitlements文件.png
3、 推送的註冊

第一步: 導入 #import

ifdef NSFoundationVersionNumber_iOS_9_x_Max

import

endif

第二步:我們需要在
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions中註冊通知,代碼如下

  • (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions {
    [self replyPushNotificationAuthorization:application];
    return YES;
    }

pragma mark - 申請通知權限

// 申請通知權限
- (void)replyPushNotificationAuthorization:(UIApplication *)application{

if (IOS10_OR_LATER) {
    //iOS 10 later
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //必須寫代理,不然無法監聽通知的接收與點擊事件
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error && granted) {
            //用戶點擊允許
            NSLog(@"註冊成功");
        }else{
            //用戶點擊不允許
            NSLog(@"註冊失敗");
        }
    }];

    // 可以通過 getNotificationSettingsWithCompletionHandler 獲取權限設置
    //之前註冊推送服務,用戶點擊了同意還是不同意,以及用戶之後又做了怎樣的更改我們都無從得知,現在 apple 開放了這個 API,我們可以直接獲取到用戶的設定信息了。注意UNNotificationSettings是隻讀對象哦,不能直接修改!
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSLog(@"========%@",settings);
    }];
}else if (IOS8_OR_LATER){
    //iOS 8 - iOS 10系統
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [application registerUserNotificationSettings:settings];
}else{
    //iOS 8.0系統以下
    [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
}

//註冊遠端消息通知獲取device token
[application registerForRemoteNotifications];

}
上面需要注意:

  1. 必須寫代理,不然無法監聽通知的接收與點擊事件
    center.delegate = self;

下面是我在項目裏定義的宏

define IOS10_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)

define IOS9_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)

define IOS8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

define IOS7_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

  1. 之前註冊推送服務,用戶點擊了同意還是不同意,以及用戶之後又做了怎樣的更改我們都無從得知,現在 apple 開放了這個 API,我們可以直接獲取到用戶的設定信息了。注意UNNotificationSettings是隻讀對象哦,不能直接修改!只能通過以下方式獲取
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
    NSLog(@”========%@”,settings);
    }];
    打印信息如下:
    ========

pragma mark - 獲取device Token

//獲取DeviceToken成功
- (void)application:(UIApplication )application didRegisterForRemoteNotificationsWithDeviceToken:(NSData )deviceToken{

//解析NSData獲取字符串
//我看網上這部分直接使用下面方法轉換爲string,你會得到一個nil(別怪我不告訴你哦)
//錯誤寫法
//NSString *string = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];


//正確寫法
NSString *deviceString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceString = [deviceString stringByReplacingOccurrencesOfString:@" " withString:@""];

NSLog(@"deviceToken===========%@",deviceString);

}

//獲取DeviceToken失敗
- (void)application:(UIApplication )application didFailToRegisterForRemoteNotificationsWithError:(NSError )error{
NSLog(@”[DeviceToken Error]:%@\n”,error.description);
}
5、這一步吊了,這是iOS 10系統更新時,蘋果給了我們2個代理方法來處理通知的接收和點擊事件,這兩個方法在的協議中,大家可以查看下。

@protocol UNUserNotificationCenterDelegate

@optional

// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
- (void)userNotificationCenter:(UNUserNotificationCenter )center willPresentNotification:(UNNotification )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);

// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter )center didReceiveNotificationResponse:(UNNotificationResponse )response withCompletionHandler:(void(^)())completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;

@end
此外,蘋果把本地通知跟遠程通知合二爲一。區分本地通知跟遠程通知的類是UNPushNotificationTrigger.h類中,UNPushNotificationTrigger的類型是新增加的,通過它,我們可以得到一些通知的觸發條件 ,解釋如下:

UNPushNotificationTrigger (遠程通知) 遠程推送的通知類型
UNTimeIntervalNotificationTrigger (本地通知) 一定時間之後,重複或者不重複推送通知。我們可以設置timeInterval(時間間隔)和repeats(是否重複)。
UNCalendarNotificationTrigger(本地通知) 一定日期之後,重複或者不重複推送通知 例如,你每天8點推送一個通知,只要dateComponents爲8,如果你想每天8點都推送這個通知,只要repeats爲YES就可以了。
UNLocationNotificationTrigger (本地通知)地理位置的一種通知,
當用戶進入或離開一個地理區域來通知。
現在先提出來,後面我會一一代碼演示出每種用法。還是回到兩個很吊的代理方法吧

pragma mark - iOS10 收到通知(本地和遠端) UNUserNotificationCenterDelegate

//App處於前臺接收通知時
- (void)userNotificationCenter:(UNUserNotificationCenter )center willPresentNotification:(UNNotification )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{

//收到推送的請求
UNNotificationRequest *request = notification.request;

//收到推送的內容
UNNotificationContent *content = request.content;

//收到用戶的基本信息
NSDictionary *userInfo = content.userInfo;

//收到推送消息的角標
NSNumber *badge = content.badge;

//收到推送消息body
NSString *body = content.body;

//推送消息的聲音
UNNotificationSound *sound = content.sound;

// 推送消息的副標題
NSString *subtitle = content.subtitle;

// 推送消息的標題
NSString *title = content.title;

if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //此處省略一萬行需求代碼。。。。。。
    NSLog(@"iOS10 收到遠程通知:%@",userInfo);

}else {
    // 判斷爲本地通知
    //此處省略一萬行需求代碼。。。。。。
    NSLog(@"iOS10 收到本地通知:{\\\\nbody:%@,\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge:%@,\\\\nsound:%@,\\\\nuserInfo:%@\\\\n}",body,title,subtitle,badge,sound,userInfo);
}


// 需要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以設置
completionHandler(UNNotificationPresentationOptionBadge|
                  UNNotificationPresentationOptionSound|
                  UNNotificationPresentationOptionAlert);

}

//App通知的點擊事件
- (void)userNotificationCenter:(UNUserNotificationCenter )center didReceiveNotificationResponse:(UNNotificationResponse )response withCompletionHandler:(void (^)())completionHandler{
//收到推送的請求
UNNotificationRequest *request = response.notification.request;

//收到推送的內容
UNNotificationContent *content = request.content;

//收到用戶的基本信息
NSDictionary *userInfo = content.userInfo;

//收到推送消息的角標
NSNumber *badge = content.badge;

//收到推送消息body
NSString *body = content.body;

//推送消息的聲音
UNNotificationSound *sound = content.sound;

// 推送消息的副標題
NSString *subtitle = content.subtitle;

// 推送消息的標題
NSString *title = content.title;

if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    NSLog(@"iOS10 收到遠程通知:%@",userInfo);
    //此處省略一萬行需求代碼。。。。。。

}else {
    // 判斷爲本地通知
    //此處省略一萬行需求代碼。。。。。。
    NSLog(@"iOS10 收到本地通知:{\\\\nbody:%@,\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge:%@,\\\\nsound:%@,\\\\nuserInfo:%@\\\\n}",body,title,subtitle,badge,sound,userInfo);
}

//2016-09-27 14:42:16.353978 UserNotificationsDemo[1765:800117] Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.
completionHandler(); // 系統要求執行這個方法

}
需要注意的:

1.下面這個代理方法,只會是app處於前臺狀態 前臺狀態 and 前臺狀態下才會走,後臺模式下是不會走這裏的
- (void)userNotificationCenter:(UNUserNotificationCenter )center willPresentNotification:(UNNotification )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler

2.下面這個代理方法,只會是用戶點擊消息纔會觸發,如果使用戶長按(3DTouch)、Action等並不會觸發。
- (void)userNotificationCenter:(UNUserNotificationCenter )center didReceiveNotificationResponse:(UNNotificationResponse )response withCompletionHandler:(void (^)())completionHandler

3.點擊代理最後需要執行:completionHandler(); // 系統要求執行這個方法
不然會報:
2016-09-27 14:42:16.353978 UserNotificationsDemo[1765:800117] Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.

4.不管前臺後臺狀態下。推送消息的橫幅都可以展示出來!後臺狀態不用說,前臺時需要在前臺代理方法中設置 ,設置如下:
// 需要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以設置
completionHandler(UNNotificationPresentationOptionBadge|
UNNotificationPresentationOptionSound|
UNNotificationPresentationOptionAlert);
6、 iOS 10之前接收通知的兼容方法

pragma mark -iOS 10之前收到通知

  • (void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo {
    NSLog(@”iOS6及以下系統,收到通知:%@”, userInfo);
    //此處省略一萬行需求代碼。。。。。。
    }

  • (void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@”iOS7及以上系統,收到通知:%@”, userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
    //此處省略一萬行需求代碼。。。。。。
    }
    段結:是不是以爲就結束了?NO NO NO(你以爲離開了幻境,其實才剛剛踏入幻境!)上面的介紹了基本原理、基本配置以及基本方法說明,現在做完這些工作,我們的學習纔剛剛開始!現在天時、地利、人和、可以開始下面推送coding的學習和測試了。

在用戶日常生活中會有很多種情形需要通知,比如:新聞提醒、定時吃藥、定期體檢、到達某個地方提醒用戶等等,這些功能在 UserNotifications 中都提供了相應的接口。

圖片來源於網絡.jpeg
我們先學會基本的技能簡單的推送(爬),後面在學習進階定製推送(走),最後看看能不能高級推送(飛不飛起來看個人了,我是飛不起來):

基本Local Notifications(本地推送) 和 Remote Notifications(遠程推送)
一、 基本的本地推送

本地推送生成主要流程就是:

  1. 創建一個觸發器(trigger)
  2. 創建推送的內容(UNMutableNotificationContent)
  3. 創建推送請求(UNNotificationRequest)
  4. 推送請求添加到推送管理中心(UNUserNotificationCenter)中
    1、新功能trigger可以在特定條件觸發,有三類:UNTimeIntervalNotificationTrigger、UNCalendarNotificationTrigger、UNLocationNotificationTrigger

1.1、 UNTimeIntervalNotificationTrigger:一段時間後觸發(定時推送)

//timeInterval:單位爲秒(s) repeats:是否循環提醒
//50s後提醒
UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:50 repeats:NO];
1.2 UNCalendarNotificationTrigger :調用
+ (instancetype)triggerWithDateMatchingComponents:(NSDateComponents *)dateComponents repeats:(BOOL)repeats;進行註冊;時間點信息用 NSDateComponents.(定期推送)

//在每週一的14點3分提醒
NSDateComponents *components = [[NSDateComponents alloc] init];
components.weekday = 2;
components.hour = 16;
components.minute = 3;
// components 日期
UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
1.3、UNLocationNotificationTrigger:調用
+ (instancetype)triggerWithRegion:(CLRegion *)region repeats:(BOOL)repeats;
進行註冊,地區信息使用CLRegion的子類CLCircularRegion,可以配置region屬性 notifyOnEntry和notifyOnExit,是在進入地區、從地區出來或者兩者都要的時候進行通知,這個測試過程專門從公司跑到家時刻關注手機有推送嘛,果然是有的(定點推送)

//首先得導入#import

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章