註冊(非互動式)推送通知

建議在 AppDelegate.swift 中新增註冊推送通知的邏輯,因為回撥函式(成功,失敗)將被稱為。要註冊,請執行以下操作:

let application = UIApplication.sharedApplication()
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)

然後將呼叫回撥函式 didRegisterUserNotificationSettings,在這種情況下,你只需觸發暫存器,如下所示:

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    application.registerForRemoteNotifications()
}

在這種情況下,將顯示系統警報,要求延遲接收推送通知。將呼叫以下回撥函式之一:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""
    
    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }
    
    print("Push token: \(tokenString)")
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print("didFailToRegisterForRemoteNotificationsWithError: \(error)")
            
}

在極少數情況下,不會呼叫成功或失敗的回撥函式。當你遇到 Internet 連線問題或 APNS Sandbox 已關閉時,會發生這種情況。系統對 APNS 進行 API 呼叫以進行一些驗證,如果不這樣做將導致將不會呼叫兩個回撥函式。訪問 Apple 系統狀態以確保其正常執行。