這三個名詞經常被混用,但它們的用途完全不同。
這是 APNS 用來識別「某一台裝置上的某一個 App」的不透明資料。Apple 特別強調:deviceToken 與 UIDevice 的 uniqueIdentifier 不同,因為出於安全與隱私考量,當使用者抹除裝置資料後,token 必須改變。也就是說同一支手機重裝系統,token 就會不一樣。
UUID 是一段 128 位元、32 個十六進位字元組成的字串,例如 BF930680-9994-442C-8A6C-FB4FD0707EB2。它的價值在於「真正唯一」:不會因為裝置名稱重複或掛載順序改變而混淆,因此系統層面常用它來標示儲存裝置。
UDID 是 40 個字元組成的 iOS 裝置識別碼。從 iOS 5 開始,Apple 宣布不再支援以 uniqueIdentifier 取得 UDID;2013 年更正式通知,自 5 月 1 日起使用 UDID 的 App 一律不予審核通過,官方建議改用 iOS 6 提供的 Vendor 或 Advertising 標識符。結論很明確:UDID 已經完全不能用。
deviceToken 的取得必須由 App 主動向 Apple 請求,而不是系統內建就有的。整體流程如下:
這也解釋了為什麼推送一定要有自己的伺服器:你的訊息不能直接送進手機,必須統一交由 Apple 的 APNS 代為轉發。
iOS 8 之後的註冊方式有明顯變動,因此實務上必須做版本判斷:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings
settingsForTypes:(UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound)
categories:nil];
[application registerUserNotificationSettings:settings];
} else {
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound)];
}
return YES;
}
註冊成功後,系統會回呼以下方法把 token 交給你,記得把它上傳到自己的後端:
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"%@", deviceToken);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@"%@", userInfo);
}
本地通知不需要伺服器,由 App 自己排程,適合「提醒喝水」「驗證碼倒數」這類場景。測試時必須把 App 切到背景才看得到效果。
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification != nil) {
NSDate *now = [NSDate new];
notification.fireDate = [now addTimeInterval:10.0];
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = @"要去吃晚飯了";
application.applicationIconBadgeNumber = 10;
[application scheduleLocalNotification:notification];
}
它主要有三類屬性:觸發時間與週期、通知型態(警告文字、動作按鈕標題、圖示上的數字、提示音),以及一個可放自訂資料的字典。
遠程推送只能在真機上運作。在模擬器註冊時會得到明確的錯誤訊息:remote notifications are not supported in the simulator。此外,若裝置經過越獄而未透過 iTunes 正常啟用,可能無法生成有效的裝置憑證,導致註冊失敗。
補充一點:iOS 10 之後,本地與遠程通知已統一整合進 UserNotifications 框架,上述 UILocalNotification 與 registerForRemoteNotificationTypes 等 API 皆已被標記為廢棄,新專案應直接採用 UNUserNotificationCenter。