注册(非交互式)推送通知

建议在 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 系统状态以确保其正常运行。