如何在Swift中注册远程通知时获取设备令牌

Mah*_*tla 9 apple-push-notifications ios swift

注册远程通知时,我无法接收设备令牌.我收到警报消息"Do you want to allow App X to be able to send you notificaitons",但是当我接受它时,didRegisterForRemoteNotifications不会调用该函数.我尝试了以下代码.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    var types: UIUserNotificationType = UIUserNotificationType.Badge |
        UIUserNotificationType.Alert |
        UIUserNotificationType.Sound

    var settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil )

    application.registerUserNotificationSettings( settings )
    application.registerForRemoteNotifications()

    return true
}

func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) {

    var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )

    var deviceTokenString: String = ( deviceToken.description as NSString )
        .stringByTrimmingCharactersInSet( characterSet )
        .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String

    println( deviceTokenString )

}
Run Code Online (Sandbox Code Playgroud)

我的配置文件和证书是有序的.

有其他人有这个问题吗?

Gar*_*aye 2

所以我在设备上运行我的应用程序一段时间,然后我回来看到它被application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) 突然调用了,现在它就像一个魅力!我对为什么会发生这种情况的最佳猜测是,证书和后台进行的所有其他操作都需要一些时间来配置推送通知。因此,对于遇到同样问题的人,我建议给它一些时间,然后再回来处理它,就我而言,如果有帮助的话,大约需要 12 个小时。