iOS 8 對使用者通知(User Notification)機制做了相當大的調整,遠端推送的註冊流程也随之改變。以下分兩部分說明。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (SYSTEM_VERSION >= 8.0) {
// iOS 8:必須先註冊「使用者通知設定」,系統才會跳出詢問授權的 dialog
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
// iOS 7 及更早:直接註冊遠端通知類型
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)];
}
return YES;
}關鍵差異在於:iOS 8 之後,registerForRemoteNotificationTypes: 不能單獨呼叫。必須先透過 registerUserNotificationSettings: 註冊一組設定,系統才會詢問使用者;使用者同意後,才會回呼 didRegisterUserNotificationSettings:,你要在這個回呼裡「再一次」呼叫 registerForRemoteNotifications 才真正完成 device token 的申請。
// 使用者同意接收通知後呼叫,在此真正向 APNs 申請 token
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
#if !TARGET_IPHONE_SIMULATOR
// 模擬器無法取得 device token,故跳過
[application registerForRemoteNotifications];
#endif
}
// 使用者對通知採取自訂動作時呼叫(iOS 8 互動式通知)
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
completionHandler:(void (^)())completionHandler {
#if !TARGET_IPHONE_SIMULATOR
if ([identifier isEqualToString:@"customAction1"]) {
// 處理自訂動作一
} else if ([identifier isEqualToString:@"customAction2"]) {
// 處理自訂動作二
}
#endif
// 無論走哪個分支,最後都必須呼叫 completionHandler
if (completionHandler) {
completionHandler();
}
}
// 註冊失敗
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if !TARGET_IPHONE_SIMULATOR
DLog(@"Error in registration. Error: %@", error);
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Push notification registering error", nil)
message:[error localizedDescription]
delegate:self
cancelButtonTitle:NSLocalizedString(@"OK", nil)
otherButtonTitles:nil];
[alertView show];
#endif
}
// 收到遠端通知
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
// 在此處理通知內容
#endif
}#if !TARGET_IPHONE_SIMULATOR 為什麼必要。模擬器無法向 APNs 註冊,也不會有 device token。若不加上這個條件判斷,在模擬器上執行就會直接走進失敗回呼,甚至造成流程卡住。
device token 要交給自己的伺服器。APNs 只認 token,推送訊息是由你的後端發起的。所以通常在 didRegisterForRemoteNotificationsWithDeviceToken: 中把 token 轉成字串後上傳存檔,後端才能對特定裝置發送通知。token 會在 App 重裝、系統還原或長時間未使用後改變,後端必須支援更新與作廢。
completionHandler 一定要呼叫。在 iOS 8 的 handleActionWithIdentifier: 中,系統會給你有限的時間處理動作,處理完畢必須呼叫 completionHandler 告知系統,否則可能被判定為執行超時。
此外,範例中的 [alertView release] 是 MRC 時代的寫法;若在 ARC 專案中請刪除該行,否則會編譯錯誤。