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

iOS 8 本地通知需要額外授權

編輯:iOS 開發綜合

隔了一段時間沒碰 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;
}

幾個實務重點

  • 授權狀態是綁在 App 上的:使用者一旦同意,日後刪除再重新安裝,系統仍視為已授權。若想重新測試拒絕授權的流程,得到「設定 → 通用 → 還原 → 還原位置與隱私」重置。
  • 註冊授權是非同步的,使用者按下允許後才會觸發 didRegisterUserNotificationSettings:。因此不要在註冊後立刻排程通知,應該等到這個回呼再處理。
  • 建議把註冊放在啟動流程最早階段,讓使用者第一次開啟 App 就看到請求,而不是等到觸發通知時才發現沒權限。
  • iOS 10 之後,這套 API 已被 UserNotifications 框架的 UNUserNotificationCenter requestAuthorizationWithOptions: 取代,新專案請直接採用新框架。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved