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

532 Views Asked by At

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?

2

There are 2 best solutions below

7
vadian On BEST ANSWER

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.

2
kstefanou On

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/