本文整理 iOS 推送通知的註冊流程,涵蓋權限申請、Device Token 取得,以及 iOS 10 之後全新架構的通知代理方法,並列出幾個容易踩到的雷。
在 AppDelegate 中導入 UserNotifications,並讓它符合 UNUserNotificationCenterDelegate 協議。為了相容舊版系統,建議用條件編譯包起來,避免低版本找不到標頭而報錯:
#ifdef NSFoundationVersionNumber_iOS_9_x_Max #import <UserNotifications/UserNotifications.h> #endif
註冊的時機放在 didFinishLaunchingWithOptions 裡,並依系統版本分三支處理:iOS 10 以上走 UNUserNotificationCenter,iOS 8 到 10 之間走 UIUserNotificationSettings,更舊的版本則直接註冊遠端通知型別。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self replyPushNotificationAuthorization:application];
return YES;
}
- (void)replyPushNotificationAuthorization:(UIApplication *)application {
if (IOS10_OR_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(@"註冊失敗");
}
}];
// 可隨時查詢目前的通知設定
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
NSLog(@"========%@", settings);
}];
} else if (IOS8_OR_LATER) {
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert
| UIUserNotificationTypeBadge
| UIUserNotificationTypeSound)
categories:nil];
[application registerUserNotificationSettings:settings];
} else {
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge
| UIRemoteNotificationTypeAlert
| UIRemoteNotificationTypeSound)];
}
// 無論哪個版本,最後都要註冊遠端通知以取得 device token
[application registerForRemoteNotifications];
}
這裡有個值得注意的改進:以前推送服務註冊後,使用者當初選了同意或不同意、之後又改過什麼設定,我們完全無從得知。現在 Apple 開放了查詢 API,可以直接讀取使用者的設定。不過要注意,UNNotificationSettings 是唯讀物件,不能修改,只能透過 getNotificationSettingsWithCompletionHandler 取得。
遠端推送取得 Device Token 的方式並未改變,但解析的寫法有一個常見錯誤值得提醒。
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// 錯誤寫法:直接以 UTF8 解碼,你會拿到 nil
// NSString *string = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
// 正確寫法:deviceToken 是二進位資料,需先取描述再清理
NSString *deviceString = [[deviceToken description]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceString = [deviceString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"deviceToken===========%@", deviceString);
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"[DeviceToken Error]:%@\n", error.description);
}
iOS 10 把本地通知與遠端通知整併為同一套 API,並提供兩個代理方法分別處理「送達」與「點擊」。它們都定義在 UNUserNotificationCenterDelegate 協議中。
此外,Apple 用 UNNotificationTrigger 的幾個子類來區分通知來源,透過它可以判斷觸發條件:
#pragma mark - 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;
NSString *body = content.body;
NSString *title = content.title;
NSString *subtitle = content.subtitle;
UNNotificationSound *sound = content.sound;
if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
NSLog(@"iOS10 收到遠端通知:%@", userInfo);
} else {
NSLog(@"iOS10 收到本地通知");
}
// 必須呼叫,用以決定是否提示使用者(Badge / Sound / Alert)
completionHandler(UNNotificationPresentationOptionBadge
| UNNotificationPresentationOptionSound
| UNNotificationPresentationOptionAlert);
}
#pragma mark - 使用者點擊通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
NSLog(@"iOS10 收到遠端通知:%@", userInfo);
} else {
NSLog(@"iOS10 收到本地通知");
}
completionHandler(); // 系統要求必須呼叫
}