ios swift - 将设备令牌保存为打印不同值的数据格式

问题描述

我尝试将 devicetoken 保存到 userDefaults 中以备后用。

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
}

我不知道打印值是否正确。 如何验证?或者如果我的存储机制是错误的。如何保存数据以备后用?

解决方法

Data编码为Data是多余的,直接保存token即可

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

你可以用

显示字节
print(deviceToken as NSData)

供以后使用

有什么用?发送通知的服务器需要维护令牌而不是客户端。

,

不需要使用NSKeyedArchiver,这就是你得到错误值的原因。为了在 UserDefaults 中保存数据(根本不安全):

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

为了检索它,您应该使用:

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

如果您想保护您保存的数据,我建议您使用钥匙串,请参考此处:https://fluffy.es/persist-data/