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

iOS 10 UserNotifications 框架全解:從註冊到自訂通知 UI 與 Service Extension

編輯:iOS 開發綜合

iOS 10 發布至今,該踩的坑大概也都踩過一輪了。但也正因如此,每次蘋果端出比較多的改動,反而讓做 iOS 這件事顯得有意思。

推送是 iOS 10 變動最大的區塊之一,這種量級的改動不看一遍實在說不過去,於是花了些時間把 UserNotifications 框架整體梳理了一次,記錄於此,希望對有興趣研究這個框架的朋友有幫助。

如果專案中的推送是走極光、友盟等第三方服務,照著它們的官方文件與最新 SDK 做 iOS 10 適配即可,流程並不複雜。但若想真正理解原生推送的環節,建議還是用原生實作,本文示範的就是原生推送。原生推送的環境配置可參考網路上寫得相當細緻的圖文教學(開發者後台介面雖已改版,但實質流程不變)。如果照著配置做完整個流程卻仍收不到遠端推送,問題很可能出在後端 PHP 端的互動,這時可以改用 PushMeBody 之類的工具發送測試推送,直接把印出的 device token 貼進去即可,不必去掉空格。

為了凸顯與舊用法的異同,本文盡量以對照方式說明。所有程式碼都放在 RITL/RITLPushNoticationDemo,若有幫助歡迎 Star 支持;發現問題也請不吝指正。

推送的註冊

註冊位置沒有變化,仍在 AppDelegate 的 application:didFinishLaunchingWithOptions: 中。為了精簡程式碼,我把註冊邏輯封裝進 RITLNotificationManager,該方法內只需一行:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 清除起始的 badge 數
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // 註冊所有推送
    [[RITLNotificationManager sharedInstance] registerRemoteNotificationsApplication:self];
    return YES;
}

註冊的具體實作

RITLNotificationManager 的介面宣告如下(Demo 中用預編譯區分版本,實務上建議直接拆成不同方法,依系統版本呼叫即可):

/// 註冊遠端推送
#ifdef __IPHONE_10_0
- (void)registerRemoteNotificationsApplication:(id<UNUserNotificationCenterDelegate>)application;
#else
- (void)registerRemoteNotificationsApplication:(id)application;
#endif
#ifdef __IPHONE_10_0
- (void)registerRemoteNotificationsApplication:(id<UNUserNotificationCenterDelegate>)application
#else
- (void)registerRemoteNotificationsApplication:(id)application
#endif
{
#ifdef __IPHONE_10_0
    // 設定代理物件
    [UNUserNotificationCenter currentNotificationCenter].delegate = application;
    // 請求權限
    [[UNUserNotificationCenter currentNotificationCenter]
        requestAuthorizationWithOptions:UNAuthorizationOptionBadge
                                   |UNAuthorizationOptionSound
                                   |UNAuthorizationOptionAlert
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
    }];
#else
#ifdef __IPHONE_8_0
    // 適配 iOS 8
    [[UIApplication sharedApplication] registerUserNotificationSettings:
        [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge
                                         |UIUserNotificationTypeSound
                                         |UIUserNotificationTypeAlert
                                     categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#else
    // 適配 iOS 7
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
#endif
#endif
}

註冊結果的回呼

這部分 iOS 10 沒有改動,仍分為成功與失敗兩個方法:

// 註冊推送成功
- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 把返回的 token 交給後端
}

// 註冊推送失敗
- (void)application:(UIApplication *)application
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"remoteNotice failture = %@", error.localizedDescription);
}

舊框架下如何接收推送

Demo 中另外建立了一個類別 RITLOriginPushAppDelegate+RITLOldNotification,用來處理舊有的接收邏輯:

// 點擊遠端推送進入 App 時執行,不論 App 是被終止還是位於背景
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"%@", [[userInfo valueForKey:@"aps"] valueForKey:@"alert"]);
    [self performSelector:NSSelectorFromString(@"__showAlert:")
               withObject:@"通過點擊推送進入App" afterDelay:0];
}
// 前景收到遠端推送時執行。若已實作 iOS 10 的協議方法,此方法不會被呼叫
- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // 此時不會自動彈出通知,通常會在這裡送出一則本地通知
    completionHandler(UIBackgroundFetchResultNewData);
}
// 收到本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"本地推送啦!");
    NSString *content = [NSString stringWithFormat:@"本地通知:title = %@, subTitle = %@",
                         notification.alertBody, notification.alertTitle];
    [self performSelector:NSSelectorFromString(@"__showAlert:") withObject:content afterDelay:1];
}

UserNotifications 下的接收方式

新框架不再區分遠端與本地通知,因此只要實作 UNUserNotificationCenterDelegate 的兩個方法即可。Demo 中放在類別 RITLOriginPushAppDelegate+RITLUserNotifications:

#pragma mark - <UNUserNotificationCenterDelegate>

// App 位於前景、即將顯示通知時觸發
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        // App 正在前景使用,不需要 badge
        completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    } else {
        // 背景或非活躍狀態,需要 badge
        completionHandler(UNNotificationPresentationOptionBadge
                          | UNNotificationPresentationOptionSound
                          | UNNotificationPresentationOptionAlert);
    }
}
// 使用者回應通知後的處理,不論是哪種通知,點擊進入或回到 App 時都會觸發
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
    didReceiveNotificationResponse:(UNNotificationResponse *)response
             withCompletionHandler:(void(^)(void))completionHandler {
    UNNotification *notification = response.notification;
    // NSDate *responseDate = notification.date;      // 回應時間
    UNNotificationRequest *request = notification.request;
    // NSString *identifier = request.identifier;     // 通知標識符
    // UNNotificationTrigger *trigger = request.trigger; // 觸發通知的物件
    UNNotificationContent *content = request.content;
    NSString *alertString = content.body;            // 通知內容
    [self performSelector:NSSelectorFromString(@"__showAlert:") withObject:alertString afterDelay:1];
    // 這裡也可以做界面跳轉等操作
    completionHandler();
}

遠端推送的負載格式與預覽

配置完成後,可用 PushMeBaby 發送測試推送。負載格式如下:

{
  "aps": {
    "alert": {
      "title": "hello",
      "subtitle": "Session 01",
      "body": "it is a beautiful day"
    },
    "category": "helloIdentifier",  // 想使用自訂 UI 時,透過此值設定 request 的 identifier
    "badge": 1,
    "mutable-content": 1,           // 要啟用 Service Extension 必須帶這個欄位
    "sound": "default",
    "image": "https://picjumbo.imgix.net/HNCK8461.jpg?q=40&w=200&sharp=30"
  }
}

Demo 中實際用於測試的負載比較簡單:

{ "aps": { "alert": "This is My message Yue.", "badge": "1", "mutable-content": 1 } }

// pushMeBody 中填入的字串
self.payload = @"{\"aps\":{\"alert\":\"This is My message Yue.\",\"badge\":\"1\",\"mutable-content\":1}}";

背景收到推送、3D Touch 展開,以及點擊進入 App 後的呈現效果:

本地推送

封裝的類別介面

Demo 中大部分測試都用本地推送,因此把功能封裝成 RITLPushMessageManager:

/// iOS 10 之前的本地推送
- (void)pushLocationNotificationBeforeiOS10;

// 因為 iOS 10 的通知可更新,這裡補了一個列舉用於測試
typedef NS_ENUM(NSUInteger, RITLPushMessageType) {
    RITLPushMessageTypeNew = 0,   /** 推送新的通知 */
    RITLPushMessageTypeUpdate = 1 /** 更新現有通知 */
};

/// iOS 10 之後的本地推送,並依類型決定是新建還是更新
- (void)pushLocationNotification:(nullable NSArray<UNNotificationAttachment> *)attachments
                        pushType:(RITLPushMessageType)type NS_AVAILABLE_IOS(10_0);

舊框架的本地推送

這部分大家應該都很熟,用的是 iOS 10 建議淘汰的 UILocalNotification:

- (void)pushLocationNotificationBeforeiOS10 {
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.alertBody = @"RITL send a location notications (iOS9)";
#ifdef __IPHONE_8_2
    localNotification.alertTitle = @"I am SubTitle";   // iOS 8.2 才有
#endif
    localNotification.alertLaunchImage = @"Stitch.png";
#ifdef __IPHONE_8_0
    localNotification.category = RITLRequestIdentifier; // 關聯 action 的 id
#endif
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.applicationIconBadgeNumber = 1;
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

新框架的本地推送

新框架下所有通知都走 UNNotificationRequest。這裡有一個關鍵限制:媒體檔放在 UNNotificationAttachment 中,但路徑必須是本地路徑。若是網路圖,得先下載到本地再傳入;另外 attachment 初始化失敗會拋出例外導致崩潰,實務上務必處理錯誤。Demo 的作法是從相簿挑一張圖存到本地,再把路徑帶進去:

- (void)pushLocationNotification:(NSArray<UNNotificationAttachment> *)attachments
                        pushType:(RITLPushMessageType)type {
    NSString *subTitle = (type == RITLPushMessageTypeNew
                          ? @"I am a new SubTitle" : @"I am a update SubTitle");

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.body = @"RITL send a location notications";
    content.subtitle = subTitle;
    content.launchImageName = @"Stitch.png";
    content.categoryIdentifier = RITLRequestIdentifier;
    content.sound = [UNNotificationSound defaultSound];
    content.badge = @1;
    content.userInfo = @{@"RITL": @"I am RITL.", @"network": @"https://www.baidu.com"};
    content.attachments = attachments;

    // 延時觸發
    UNTimeIntervalNotificationTrigger *trigger = [UNNotificationTrigger defaultTimeIntervalNotificationTrigger];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:RITLRequestIdentifier
                                                                          content:content
                                                                          trigger:trigger];
    // 若是更新,先移除已送出的通知
    if (type == RITLPushMessageTypeUpdate) {
        [[UNUserNotificationCenter currentNotificationCenter]
            removeDeliveredNotificationsWithIdentifiers:@[RITLRequestIdentifier]];
    }
    [[UNUserNotificationCenter currentNotificationCenter]
        addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"error = %@", error.localizedDescription);
        }
    }];
}

UNNotificationTrigger 觸發條件

這個類別負責定義通知的觸發條件。Demo 在 UNNotificationTrigger+RITLConveniceInitialize 類別中提供了三種預設條件:

/// 預設的延時觸發
+ (UNTimeIntervalNotificationTrigger *)defaultTimeIntervalNotificationTrigger {
    return [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
}
/// 預設的日曆觸發:每天 7 點
+ (UNCalendarNotificationTrigger *)defaultCalendarNotificationTrigger {
    NSDateComponents *dateComponents = [NSDateComponents new];
    dateComponents.hour = 7;
    return [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
}
/// 預設的區域觸發
+ (UNLocationNotificationTrigger *)defaultLocationNotificationTrigger {
    // CLRegion 的舊初始化方法在 iOS 7 已標記廢棄,改用其子類 CLCircularRegion
    CLLocationCoordinate2D coordinate2D = coordinate2DMake(100, 100);
    CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:coordinate2D
                                                                radius:200
                                                            identifier:locationTriggerIdentifier];
    return [UNLocationNotificationTrigger triggerWithRegion:region repeats:NO];
}

本地推送預覽

選擇從相簿挑一張圖來完成本地推送,主要思路是先把圖存到本地,再據此建立 attachment:

+ (NSArray<UNNotificationAttachment> *)defaultNotificationAttachmentsWithImage:(UIImage *)image {
    if (image == nil) return nil;

    NSMutableArray<UNNotificationAttachment> *attachments = [NSMutableArray arrayWithCapacity:1];
    [RITLPushFilesManager saveImage:image key:imageTransformPathKey];

    NSError *error;
    UNNotificationAttachment *attachment =
        [UNNotificationAttachment attachmentWithIdentifier:attachmentIdentifier
                                                    URL:[RITLPushFilesManager imageUrlPathWithKey:imageTransformPathKey]
                                                options:nil
                                                  error:&error];
    NSAssert(error == nil, error.localizedDescription);
    [attachments addObject:attachment];
    return [attachments mutableCopy];
}

通知策略(Category)

策略可以理解為通知的「類別」。用 3D Touch 展開通知後會出現一排動作按鈕,目前上限為 4 個,而這機制最早出現在 iOS 8.0。Demo 中把新增策略的邏輯封裝進 RITLPushCategoryManager。

舊框架下的策略定義

// 為 Demo 新增預設策略(iOS 10 之前)
+ (UIUserNotificationCategory *)addDefaultCategorysBeforeiOS10 {
    // 普通回應動作
    UIMutableUserNotificationAction *foregroundAction = [UIMutableUserNotificationAction new];
    foregroundAction.identifier = foregroundActionIdentifier;
    foregroundAction.title = @"收到了";
    foregroundAction.activationMode = UIUserNotificationActivationModeForeground;

    // 文字輸入型動作
    UIMutableUserNotificationAction *destructiveTextAction = [UIMutableUserNotificationAction new];
    destructiveTextAction.identifier = destructiveTextActionIdentifier;
    destructiveTextAction.title = @"我想說兩句";
    destructiveTextAction.activationMode = UIUserNotificationActivationModeForeground;
    destructiveTextAction.behavior = UIUserNotificationActionBehaviorTextInput;
    destructiveTextAction.authenticationRequired = NO;
    destructiveTextAction.destructive = YES;

    UIMutableUserNotificationCategory *category = [UIMutableUserNotificationCategory new];
    category.identifier = RITLRequestIdentifier;
    [category setActions:@[foregroundAction, destructiveTextAction]
              forContext:UIUserNotificationActionContextDefault];
    return [category copy];
}
// 註冊推送時,把 category 以 NSSet 形式傳入 registerUserNotificationSettings: 的第二個參數即可

新框架下的策略定義

UserNotifications 提供了不少便利建構器,程式碼精簡許多(因為很長所以保持單行):

+ (void)addDefaultCategorys {
    // 普通回應動作
    UNNotificationAction *foregroundAction =
        [UNNotificationAction actionWithIdentifier:foregroundActionIdentifier
                                            title:@"收到了"
                                          options:UNNotificationActionOptionForeground];

    // 文字輸入型動作
    UNTextInputNotificationAction *destructiveTextAction =
        [UNTextInputNotificationAction actionWithIdentifier:destructiveTextActionIdentifier
                                                    title:@"我想說兩句"
                                                  options:UNNotificationActionOptionDestructive
                                                        |UNNotificationActionOptionForeground
                                       textInputButtonTitle:@"發送"
                                       textInputPlaceholder:@"想說什麼?"];

    // 建立策略物件。此處的 identifier 必須與 UNNotificationRequest 使用的相同才會觸發
    UNNotificationCategory *category =
        [UNNotificationCategory categoryWithIdentifier:RITLRequestIdentifier
                                              actions:@[foregroundAction, destructiveTextAction]
                                    intentIdentifiers:@[foregroundActionIdentifier, destructiveTextActionIdentifier]
                                              options:UNNotificationCategoryOptionCustomDismissAction];

    [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:
        [NSSet setWithObjects:category, nil]];
}

如何回應策略動作

在 userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: 開頭加入策略判斷即可:

if ([response.actionIdentifier isEqualToString:foregroundActionIdentifier]) {
    [self performSelector:NSSelectorFromString(@"__showAlert:")
               withObject:@"我是第一個策略動作,收到了" afterDelay:0];
    completionHandler();
    return;
} else if ([response.actionIdentifier isEqualToString:destructiveTextActionIdentifier]) {
    NSString *text = ((UNTextInputNotificationResponse *)response).userText;
    [self performSelector:NSSelectorFromString(@"__showAlert:")
               withObject:[NSString stringWithFormat:@"我是第二個文本動作,我輸入的文字是:%@", text]
               afterDelay:0];
    completionHandler();
    return;
}

3D Touch 展開策略、回應文字輸入,以及最終反應的預覽:

推送擴充:NotificationContentExtension

建立方式

步驟與 Widget 這類 Today Extension 相同:File → New → Target → Notification Content Extension。

建立完成後預設的控制器名為 NotificationViewController,Demo 中只改了名字,檔案結構如下:

若涉及 UI 繪製或資料、程式碼共享,做法與一般擴充開發一致,可參考作者先前關於 Widget(Today Extension)擴充開發的文章。

這裡要注意:建立擴充之後,如果本地通知仍呈現預設樣式,請檢查 Info.plist 中 NSExtension → NSExtensionAttributes → UNNotificationExtensionCategory(預設是 String),它的值必須與 UNNotificationRequest 的 identifier 相符才會觸發;若要支援多個通知,可把該欄位改成陣列。

Demo 中建立 UNNotificationRequest 的程式碼:

NSString * const RITLRequestIdentifier = @"com.yue.originPush.myNotificationCategory";

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:RITLRequestIdentifier
                                                                      content:content
                                                                      trigger:trigger];

為確保能觸發自訂通知 UI,Demo 的 plist 設定如下:

Demo 仍用 storyboard 佈局,因為重點是研究框架,所以畫面很簡單:

UNNotificationContentExtension 協議

這個協議很單純,一個必作方法、一個可選方法:

// 收到通知後的回呼,必須實作
- (void)didReceiveNotification:(UNNotification *)notification {
    UNNotificationContent *content = notification.request.content;
    NSString *customTitle = content.body;
    UIImage *image = [UIImage imageNamed:content.launchImageName];

    self.customlabel.text = customTitle;      // 擴充內自訂的標籤
    self.customimageView.image = image;       // 通知自帶的圖片
    self.attachmentImageView.image = nil;     // 直接用 attachment 的路徑載入即可
    // 若是遠端推送的網路圖還沒載入也沒關係,後面的 NotificationServiceExtension 就是為此而生
}

可選方法的作用:當通知以自訂 UI 呈現時,點擊或回應策略動作會優先走這個方法,並由它的回呼決定後續行為。

typedef NS_ENUM(NSUInteger, UNNotificationContentExtensionResponseOption) {
    UNNotificationContentExtensionResponseOptionDoNotDismiss,           // 預設:不關閉
    UNNotificationContentExtensionResponseOptionDismiss,                // 關閉
    UNNotificationContentExtensionResponseOptionDismissAndForwardAction // 關閉並交給主 App 處理
};
// 展開後的通知收到點擊回應
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response
                     completionHandler:(void (^)(UNNotificationContentExtensionResponseOption option))completion {
    // 關閉並回到主 App 處理,之後才會走 UNUserNotificationCenter 的協議方法
    completion(UNNotificationContentExtensionResponseOptionDismissAndForwardAction);
}

自訂通知 UI、策略文字輸入,以及最終回應的預覽:

推送擴充:NotificationServiceExtension

在建立 Target 的清單中,Notification Content Extension 旁邊還有這個選項:

它的用途是處理遠端推送的資料,能給我們最長約 30 秒的時間去修改通知內容,或下載通知中附帶的圖片、影片、音訊資源。

多數程式碼系統已代為產生,這裡只貼上 Demo 中的一小段實作,作用是在收到遠端推送時改寫內容:

// 大約有 30 秒的時間限制
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request
                   withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    // 修改通知內容
    self.bestAttemptContent.body = @"我是在Service裡面修改後的title";

    // 若含有圖片、影片、音訊的 url,可以在這裡下載,再建立 UNNotificationAttachment 並賦值給 attachments

    self.contentHandler(self.bestAttemptContent);
}

另一個方法則是在擴充即將被系統終止前給出的最後機會,用它送出目前盡力完成的通知內容,否則系統會沿用原始的推送負載:

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content,
    // otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

用 pushMeBody 送一次遠端推送,3D Touch 展開與點擊進入後的結果:

更多內容請見 GitHub 上的 Demo。

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