您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 8 的通知註冊改動導致百度推送收不到訊息的解法

編輯:iOS 相關資訊

App 升上 iOS 8 之後,原本運作正常的百度推送突然收不到訊息,問題幾乎都出在遠端通知的註冊方式變了。

原因

iOS 8 把「註冊使用者可接收哪些通知」與「向 APNs 註冊裝置」拆成了兩個步驟。舊寫法直接呼叫 registerForRemoteNotificationTypes:,在 iOS 8 上不會真正完成註冊流程,於是 device token 拿不到,推送到自然也收不到。

修正後的註冊程式碼

// 消息推送註冊
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:
        [UIUserNotificationSettings
            settingsForTypes:(UIUserNotificationTypeSound |
                              UIUserNotificationTypeAlert |
                              UIUserNotificationTypeBadge)
                  categories:nil]];

    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeSound |
         UIRemoteNotificationTypeAlert)];
}

關鍵差異是:iOS 8 必須先呼叫 registerUserNotificationSettings: 告訴系統 App 想用哪幾種提示方式,等使用者授權後,再由 registerForRemoteNotifications 向 APNs 取得 token。兩個呼叫都不能省。

取消推送

取消的做法與註冊對稱:

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
    (UIRemoteNotificationTypeBadge |
     UIRemoteNotificationTypeSound |
     UIRemoteNotificationTypeAlert)];

更明確的寫法是設定 application.currentNotificationSettings.types 為 UIUserNotificationTypeNone,或直接呼叫 unregisterForRemoteNotifications。不過要注意,iOS 8.2 之後 Apple 調整了這組 API 的行為,unregisterForRemoteNotifications 不再清除裝置的 APNs token,只會停止接收通知。若你的後端依賴 token 判斷是否停推,需要自行在伺服器端記錄使用者的訂閱狀態。

排查清單

如果改完仍收不到,依序檢查這幾項:一, provisioning profile 是否開啟 Push Notifications 能力;二, Debug 與 Release 使用不同的 profile 與憑證,測試時是否用錯環境(sandbox / production);三, didRegisterForRemoteNotificationWithDeviceToken 是否正確回傳 token 給百度雲與自己的後端;四, App 的 Bundle Identifier 是否與後台設定的 App ID 完全一致。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved