iosSwifty
iosSwifty

Reputation: 15

ios swift - Save device token as data format printing different values

I tried save devicetoken into userDefaults for later use.

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print(deviceToken) // value print as 32 bytes

 let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: deviceToken)
        UserDefaults.standard.set(encodedData , forKey: "deviceToken")


 let decoded  = UserDefaults.standard.data(forKey: "deviceToken")
print(decoded) // value print as 172 bytes
}

i don't know whether the printing value is correct or not. how to verify it? or if my storing mechanism is wrong. how can i save data for later usage?

Upvotes: 0

Views: 655

Answers (2)

kstefanou
kstefanou

Reputation: 617

there is no need of use NSKeyedArchiver, this is the reason that you get a wrong value. In order to save data in UserDefaults (which is not safe at all):

UserDefaults.standard.set(deviceToken, forKey: "kDeviceToken")

In order to retrieve it you should use :

let deviceToken = UserDefaults.standard.data(forKey: "kDeviceToken")

If you want to secure the data that you are saving I recommend you to use Keychain, reference here: https://fluffy.es/persist-data/

Upvotes: 0

vadian
vadian

Reputation: 285270

Encoding Data to Data is redundant, just save the token directly

UserDefaults.standard.set(deviceToken, forKey: "deviceToken")

and you can display the bytes with

print(deviceToken as NSData)

for later use

What use? The server which sends the notification needs to maintain the token but not the client.

Upvotes: 0

Related Questions