Tolgay Toklar
Tolgay Toklar

Reputation: 4343

Saving deviceToken to NSUserDefaults

I am trying to save device token to NSUserDefaults but I couldn't do it.

My code:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    var currentToken=preferences.stringForKey(pushTokenKey)
    if currentToken != deviceToken {
        var dataString = NSString(data: deviceToken, encoding:NSUTF8StringEncoding) as String?
        self.preferences.setValue(dataString, forKey: pushTokenKey)
        self.preferences.synchronize()
    }
}

You can see i am comparing the tokens and if they are not same i am updating it. But it is always saving as nil I guess because deviceToken is NSData.

How can I resolve this problem ?

Upvotes: 2

Views: 2253

Answers (2)

Michael
Michael

Reputation: 6513

The device token should never be saved to anywhere. Just keep it in memory in some global variable. When you re-open the app, you will get the same token again from the APNS-API. Your delegate method will be called again, and the user will not be asked again if he already agreed to give you the token in the past. The documentation explicitely says that you should not save it!

The way your method works, you could also just save the token in any case, no matter if it changed or not, and it would do exactly the same, because the pattern is that

if(a != b) {
    b = a;
}

is equivalent to just

b = a;

Furthermore, the device token is binary data, so it is just not UTF-8 encoded (you tried to convert it to a string, interpreting the binary data as NSUTF8StringEncoding). In 99% of cases, it will not be possible to encode it as UTF-8, for this reason you get nil.

Furthermore, even if the token would be UTF-8 (which it will be in 1 out of 10^16 cases), the comparison will still say that they are not equal, because you are comparing an NSData binary with an NSString.

Upvotes: 3

Arbitur
Arbitur

Reputation: 39091

Reason why you get nil is because it is not able to turn that NSData to NSString

By using deviceToken.description you will get the string token.

var currentToken=preferences.stringForKey(pushTokenKey)

if currentToken != deviceToken.description { // Here you were comparing  String and NSData ?? :S
    var dataString = deviceToken.description
    self.preferences.setValue(dataString, forKey: pushTokenKey)
    self.preferences.synchronize()
}

Upvotes: 0

Related Questions