Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get device token when registering for remote notifications in Swift

I can not receive the device token when registering for remote notifications. I get the alert message "Do you want to allow App X to be able to send you notificaitons", but when I accept it, the didRegisterForRemoteNotifications function is not called. I tried the following code.

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 )

}

My provisioning profile and certificates are in order.

Has someone else had this problem?

like image 978
Mahesh Kolagatla Avatar asked Oct 13 '15 18:10

Mahesh Kolagatla


2 Answers

So I was running my app on a device for a while and I came back to see that the application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) had been called out of blue and now it works like a charm! My best guess to why it is that this happened would be that it just took some time for the certificates and everything else that goes on in the background to configure push notifications to be configured. So for anyone that is having the same problem I suggest giving it some time and then coming back to it, in my case it took about 12 hours if its any help.

like image 190
Garret Kaye Avatar answered Sep 29 '22 03:09

Garret Kaye


Sometimes the sandbox apns is down like it happened yesterday, at that time the delegates are not called for device token.

like image 35
Garima Avatar answered Sep 29 '22 04:09

Garima