[英]ios swift - Save device token as data format printing different values
我嘗試將 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
}
我不知道打印值是否正確。 如何驗證? 或者如果我的存儲機制是錯誤的。 如何保存數據以備后用?
Encoding Data
to 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")
如果你想保護你保存的數據,我建議你使用 Keychain,參考這里: https://fluffy.es/persist-data/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.