玩轉 iOS 10 推送 —— UserNotifications Framework(上)

iOS 10 came

在今年 6月14號 蘋果開發者大會 WWDC 2016 以後,筆者趕忙就去 apple 的開發者網站下載了最新的 Xcode 8 betaiOS 10 beta,而後在本身的手機上裝了 iOS 10 beta ,狠狠地體驗了一把。
能夠說 iOS 10 不管從界面風格,仍是 Framework 都作了不少改動。最直觀的感覺就是界面的圓角增多了,系統動畫更加多樣和流暢,系統 App 的功能也變得更豐富了。javascript

而 iOS 10 裏的推送功能,也較以前更增強大,
今天咱們就來聊聊 iOS 10 裏的推送功能。java

Notifications before iOS 10

首先咱們一塊兒簡單回顧下 iOS 10 之前的推送服務。
iOS 推送分爲 Local Notifications(本地推送) 和 Remote Notifications(遠程推送),先看 2 張圖:ios

Local Notifications

Remote Notifications

簡單的說就是本地推送經過 App 本地定製,加入到系統的 Schedule 裏,而後在指定的時間推送指定文字。而遠程推送經過服務端向蘋果推送服務器 Apple Push Notification Service (APNs) 發送 Notification Payload,以後 APNs 再將推送下發到指定設備的 指定 App 上。
以及 iOS 7 以後在不顯式地彈窗打擾用戶的狀況下,進行的靜默推送服務器

Silent Push

具體作法能夠參考 iOS 7 Background Remote Notificationapp

User Notifications Framework


好,扯了這麼多,該進入今天的正題了 —— User Notifications Framework 。
首先在 AppDelegate.m動畫

import
#import <UserNotifications/UserNotifications.h>複製代碼
註冊推送

如下分別是 iOS 10 以前和以後的註冊方式,其中的 UNAuthorizationOptions 裏還能夠找到 1 個 UNAuthorizationOptionCarPlay 的值是專爲車載系統定製的值。網站

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //iOS 10 before
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [application registerUserNotificationSettings:settings];

    //iOS 10
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
        }
    }];

    return YES;
}複製代碼
Notification settings

以前註冊推送服務,ios 8 及以前使用了不一樣的 API,而且返回結果也不一樣。如今 apple 不只統一了這個 API,並且咱們能夠獲取到用戶更加詳細的設定了。spa

[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSLog(@"%@",settings);
}];複製代碼

打印得到以下信息:3d

<UNNotificationSettings: 0x16567310; 
authorizationStatus: Authorized, 
notificationCenterSetting: Enabled, 
soundSetting: Enabled, 
badgeSetting: Enabled, 
lockScreenSetting: Enabled, 
alertSetting: NotSupported,
carPlaySetting: Enabled, 
alertStyle: Banner>複製代碼
Token Registration

跟以前同樣code

[[UIApplication sharedApplication] registerForRemoteNotifications];複製代碼
Content

之前只能展現一條文字,如今能夠有 title 、subtitle 以及 body 了。


定製方法以下:

//Local Notification
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"Introduction to Notifications";
content.subtitle = @"Session 707";
content.body = @"Woah! These new notifications look amazing! Don’t you agree?";
content.badge = @1;

//Remote Notification
{
"aps" : {
    "alert" : { 
         "title" : "Introduction to Notifications", 
         "subtitle" : "Session 707",         
         "body" : "Woah! These new notifications look amazing! Don’t you agree?"
                },
    "badge" : 1
        },
}複製代碼
Triggers

又是一個新的功能,有三種

  • UNTimeIntervalNotificationTrigger
  • UNCalendarNotificationTrigger
  • UNLocationNotificationTrigger
//2 分鐘後提醒
UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:120 repeats:NO];

//每小時重複 1 次喊我喝水
UNTimeIntervalNotificationTrigger *trigger2 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3600 repeats:YES];

//每週一早上 8:00 提醒我給老婆作早飯
NSDateComponents *components = [[NSDateComponents alloc] init];
components.weekday = 2;
components.hour = 8;
UNCalendarNotificationTrigger *trigger3 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];

//#import <CoreLocation/CoreLocation.h>
//一到麥當勞就喊我下車
CLRegion *region = [[CLRegion alloc] init];
UNLocationNotificationTrigger *trigger4 = [UNLocationNotificationTrigger triggerWithRegion:region repeats:NO];複製代碼
Add Request
NSString *requestIdentifier = @"sampleRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier
                                                                          content:content
                                                                          trigger:trigger1];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

}];複製代碼

推送小結

而後整個推送的過程就變成了醬紫:

  • Local Notifications 經過定義 ContentTriggerUNUserNotificationCenter 進行 request 這三部曲來實現。
  • Remote Notifications 則向 APNs 發送 Notification Payload
Notification Handling

設定了推送,而後就結束了?iOS 10 並無這麼簡單!
經過實現協議,使 App 處於前臺時捕捉並處理即將觸發的推送:

@interface AppDelegate () <UNUserNotificationCenterDelegate>

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{

    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);

}複製代碼

讓它只顯示 alert 和 sound ,而忽略 badge 。

Notification Management

完全掌控整個推送週期:

  • Local Notification 經過更新 request
  • Remote Notification 經過新的字段 apns-collapse-id

經過以前的 addNotificationRequest: 方法,在 id 不變的狀況下從新添加,就能夠刷新原有的推送。

NSString *requestIdentifier = @"sampleRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier
                                                                      content:newContent
                                                                      trigger:newTrigger1];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

}];複製代碼

刪除計劃的推送:

[center removePendingNotificationRequestsWithIdentifiers:@[requestIdentifier]];複製代碼

此外 UNUserNotificationCenter.h 中還有諸如刪除全部推送、查看已經發出的推送、刪除已經發出的推送等等強大的接口。

刷新原有的推送後,在通知中心的顯示裏,也會有相應的變化,這裏注意第 2 條信息,如今比分是 1:0


比分刷新後爲 1:1,在不產生新的推送條目的狀況下位置被前置了!

試想利用這個方法,不斷的刷新推送,是否是就能夠作到讓本身 App 的推送內容始終展現在用戶手機通知中心的最頂端,力壓其他全部內容了呢?總感受有點不厚道啊~

Advanced Notifications


關於推送的更多相似 Media Attachments 的高級功能,咱們將在下一篇裏詳細討論。

Media Attachments

爲推送添加更多媒體附件,諸如圖片、音樂

繼續瀏覽下一篇 玩轉 iOS 10 推送 (中)

相關文章
相關標籤/搜索