您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 10 通知系統新特性總整理:內容、觸發器與更新機制

編輯:iOS 開發綜合

研究過 iOS 10 的通知機制後,可以感覺出改動幅度不小。整理起來主要是這幾點:

1. 內容更豐富,從原本只有 alert,擴充到 title、subtitle、body。
2. 所有通知都統一由 trigger 觸發。
3. 可以掛附件——圖片、音訊、視訊都行,讓通知能呈現的資訊大幅增加。
4. 通知內容可以在送達前被更新。

引入新框架

加入 UserNotifications.framework,並引入 <UserNotifications/UserNotifications.h>。

註冊推送

iOS 10 起,所有通知(遠端與本地)都由 UNUserNotificationCenter 管理,註冊授權也走它:

// iOS 8 以下
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
                              | UIRemoteNotificationTypeAlert
                              | UIRemoteNotificationTypeSound];

// iOS 8 - iOS 10
[application registerUserNotificationSettings:
    [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert
                                      | UIUserNotificationTypeSound
                                      | UIUserNotificationTypeBadge
                                      categories:nil]];

// iOS 10
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert
                                       | UNAuthorizationOptionBadge
                                       | UNAuthorizationOptionSound)
                      completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];

讀取使用者設定

iOS 10 提供了 getNotificationSettingsWithCompletionHandler:,回呼帶一個 UNNotificationSettings,具備 authorizationStatus、soundSetting、badgeSetting、alertSetting、notificationCenterSetting、lockScreenSetting、carPlaySetting、alertStyle 等屬性,能精確掌握每一項授權狀態。

例如使用者按下允許之後:

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert
                                       | UNAuthorizationOptionBadge
                                       | UNAuthorizationOptionSound)
                      completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted) {
        NSLog(@"註冊通知成功");
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"%@", settings);
        }];
    } else {
        NSLog(@"註冊通知失敗");
    }
}];

印出的內容大致如下:

<UNNotificationSettings: 0x174090a90;
 authorizationStatus: Authorized,
 notificationCenterSetting: Enabled,
 soundSetting: Enabled,
 badgeSetting: Enabled,
 lockScreenSetting: Enabled,
 alertSetting: NotSupported,
 carPlaySetting: Enabled,
 alertStyle: Banner>

註冊 APNS 並取得 token

這部分與過去相同。在 application:didFinishLaunchingWithOptions: 呼叫 registerForRemoteNotifications:

[[UIApplication sharedApplication] registerForRemoteNotifications];

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0) {
    NSLog(@"deviceToken:%@", deviceToken);
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0) {
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@", error);
}

設定 action 與 category

iOS 8 以前沒有 category 這個概念;iOS 8 註冊授權時可以順帶設定;到了 iOS 10,則要另外呼叫 setNotificationCategories: 來為 center 註冊 category,再由 category 關聯一組 action。

// 建立 category
// UNNotificationActionOptionAuthenticationRequired  需要解鎖
// UNNotificationActionOptionDestructive             顯示為紅色
// UNNotificationActionOptionForeground              點擊後開啟 App
UNNotificationAction *action1 =
    [UNNotificationAction actionWithIdentifier:@"action1"
                                         title:@"策略1行為1"
                                       options:UNNotificationActionOptionForeground];

UNTextInputNotificationAction *action2 =
    [UNTextInputNotificationAction actionWithIdentifier:@"action2"
                                                 title:@"策略1行為2"
                                               options:UNNotificationActionOptionDestructive
                                  textInputButtonTitle:@"comment"
                                  textInputPlaceholder:@"reply"];

// UNNotificationCategoryOptionNone
// UNNotificationCategoryOptionCustomDismissAction    清除通知時也會走 delegate
// UNNotificationCategoryOptionAllowInCarPlay         行車模式可用
UNNotificationCategory *category1 =
    [UNNotificationCategory categoryWithIdentifier:@"category1"
                                          actions:@[action2, action1]
                                  minimalActions:@[action2, action1]
                                intentIdentifiers:@[]
                                          options:UNNotificationCategoryOptionCustomDismissAction];

UNNotificationAction *action3 =
    [UNNotificationAction actionWithIdentifier:@"action3" title:@"策略2行為1"
                                       options:UNNotificationActionOptionForeground];
UNNotificationAction *action4 =
    [UNNotificationAction actionWithIdentifier:@"action4" title:@"策略2行為2"
                                       options:UNNotificationActionOptionForeground];

UNNotificationCategory *category2 =
    [UNNotificationCategory categoryWithIdentifier:@"category2"
                                          actions:@[action3, action4]
                                  minimalActions:@[action3, action4]
                                intentIdentifiers:@[]
                                          options:UNNotificationCategoryOptionCustomDismissAction];

[[UNUserNotificationCenter currentNotificationCenter]
    setNotificationCategories:[NSSet setWithObjects:category1, category2, nil]];

設定通知內容

因為遠端與本地通知在 iOS 10 被統一,內容屬性也一致;遠端推送則需在 payload 中對應設定。UNNotificationContent 不可直接实例化,要自己組內容得用 UNMutableNotificationContent。主要屬性:

attachments(附件)、badge(角標)、body(內文)、categoryIdentifier(category 標識)、launchImageName(點通知進入時的啟動圖)、sound(聲音)、subtitle(子標題)、title(標題)、userInfo(遠端通知內容)。

UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title    = @"Test";
content.subtitle = @"1234567890";
content.body     = @"Copyright © 2016年 jpush. All rights reserved.";
content.badge    = @1;

NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"718835727" ofType:@"png"];
UNNotificationAttachment *att =
    [UNNotificationAttachment attachmentWithIdentifier:@"att1"
                                                  URL:[NSURL fileURLWithPath:path]
                                              options:nil
                                                error:&error];
if (error) {
    NSLog(@"attachment error %@", error);
}
content.attachments = @[att];

content.categoryIdentifier = @"category1";   // 對應前面註冊的 category
content.launchImageName = @"1-Eb_0OvtcxJXHZ7-IOoBsaQ";
content.sound = [UNNotificationSound defaultSound];

通知觸發器

iOS 10 的 UNNotificationTrigger 有四種:

• UNPushNotificationTrigger:由 APNS 觸發,系統自動設定,這也是區分遠端與本地通知的標識。
• UNTimeIntervalNotificationTrigger:一段時間後觸發。
• UNCalendarNotificationTrigger:指定日期觸發。
• UNLocationNotificationTrigger:依位置觸發,可選擇進入、離開或兩者。

// 10 秒後
UNTimeIntervalNotificationTrigger *trigger1 =
    [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

// 每週日早上 8:00
NSDateComponents *component = [[NSDateComponents alloc] init];
component.weekday = 1;
component.hour = 8;
UNCalendarNotificationTrigger *trigger2 =
    [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:component repeats:YES];

// 圓形區域,進入時通知
CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(80.335400, -90.009201);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:cen
                                                           radius:500.0
                                                       identifier:@"center"];
region.notifyOnEntry = YES;
region.notifyOnExit  = NO;
UNLocationNotificationTrigger *trigger3 =
    [UNLocationNotificationTrigger triggerWithRegion:region repeats:NO];

加入與更新通知

1. 建立 UNNotificationRequest,務必設定 identifier——後續查詢、更新、刪除都靠它辨識。
2. 把 request 加進 UNUserNotificationCenter 並附上 trigger,等它觸發。
3. 若另送一個 identifier 相同但內容不同的 request,就達成了「更新通知」的效果。

NSString *requestIdentifer = @"TestRequest";
UNNotificationRequest *request =
    [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger1];

[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];

// 另一處需要更新通知時
UNMutableNotificationContent *newContent = [[UNMutableNotificationContent alloc] init];
newContent.title    = @"Update";
newContent.subtitle = @"XXXXXXXXX";
newContent.body     = @"Copyright © 2016年 jpush. All rights reserved.";

UNTimeIntervalNotificationTrigger *newTrigger =
    [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];

UNNotificationRequest *newRequest =
    [UNNotificationRequest requestWithIdentifier:@"TestRequest" content:newContent trigger:newTrigger];

[[UNUserNotificationCenter currentNotificationCenter]
    addNotificationRequest:newRequest
         withCompletionHandler:^(NSError * _Nullable error) {
}];

取得與刪除通知

通知有兩種狀態:Pending(等待觸發)與 Delivered(已觸發並顯示在通知中心)。

// 取得尚未觸發的通知
[[UNUserNotificationCenter currentNotificationCenter]
    getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
    NSLog(@"pending: %@", requests);
}];

// 取得通知中心裡的通知
[[UNUserNotificationCenter currentNotificationCenter]
    getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
    NSLog(@"Delivered: %@", notifications);
}];

// 刪除指定的待發通知
[[UNUserNotificationCenter currentNotificationCenter]
    removePendingNotificationRequestsWithIdentifiers:@[@"TestRequest1"]];

// 刪除指定的已送通知
[[UNUserNotificationCenter currentNotificationCenter]
    removeDeliveredNotificationsWithIdentifiers:@[@"TestRequest2"]];

// 全部清除
[[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
[[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];

delegate

遵循 <UNUserNotificationCenterDelegate>。iOS 10 之後不再走 application:didReceiveRemoteNotification:,改由這兩個新方法統一接收與處理各類通知:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // App 在前台時收到通知
    NSLog(@"========%@", notification);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
   didReceiveNotificationResponse:(UNNotificationResponse *)response
             withCompletionHandler:(void (^)())completionHandler {
    // 點擊通知進入 App
    NSLog(@"response:%@", response);
}

關於富媒體推送的 UNNotificationServiceExtension 與 notification content extension,留待下一篇再談。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved