iosswiftnsuserdefaultsuserdefaultsdevicetoken

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?


Solution

  • 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.