隔了一段時間沒碰 UILocalNotification,這次重新接入時發現通知根本發不出來,只有在控制台看到一行警告:
Attempting to schedule a local notification <UConcreteLocalNotification: 0x174178540>{
fire date = (null), time zone = (null), repeat interval = 0,
repeat count = UILocalNotificationInfiniteRepeatCount,
next fire date ... } but haven't received permission from the user to
badge the application
查了 API 才確認:從 iOS 8 開始,本地通知改為需要使用者明確授權才能發送。這是一個安全上的合理調整,但對既有程式碼卻是破壞性變更——舊版直接 scheduleLocalNotification: 就能用,現在必須先向系統註冊並取得同意。
- (void)RegistNotificationSettings {
float sysVersion = [[UIDevice currentDevice] systemVersion].floatValue;
if (sysVersion >= 8.0) {
UIUserNotificationType type = UIUserNotificationTypeBadge
| UIUserNotificationTypeAlert
| UIUserNotificationTypeSound;
UIUserNotificationSettings *setting =
[UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:setting];
}
}
這個方法可以在需要發通知之前呼叫,也可以直接放在 App 啟動流程中:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// ... 其他初始化
[self RegistNotificationSettings];
return YES;
}
didRegisterUserNotificationSettings:。因此不要在註冊後立刻排程通知,應該等到這個回呼再處理。UserNotifications 框架的 UNUserNotificationCenter requestAuthorizationWithOptions: 取代,新專案請直接採用新框架。