首页 > 解决方案 > 如何从应用程序中删除用户默认值?

问题描述

我已经创建了登录页面。当我输入电子邮件和密码时,从 Json 返回用户 ID,然后,我将 ID 保存在用户默认值中,以便能够在我的应用程序的不同页面中使用它,但是当我在另一个页面中添加注销按钮时。注销按钮的功能是当我按下它时从用户默认值中删除 id 然后将我带到 root uiviewcontroller 但是当我注销并使用另一个帐户登录时窃取保存旧 ID。

//save id to the user default by using login button
let id = UserDefaults.standard
id.set(data.id , forKey : "ID")
id.synchronize 

//using user id with this code in diferent pages 
let user_id = UserDefaults.standard.integer(forKey : "ID")

//delete id from user default by using logout button
UserDefaults.standard.removeObject(forKey : "ID") 
userDefaults.synchronize 
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let mainScreen = UIStoryboard.init(name : "Main" , bundle : nil).instantiateViewController(withIdentifier :"BG")
appDelegate.window?.rootViewController =   mainScreen

标签: swiftnsuserdefaults

解决方案


我们有两种选择,一种是设置为空或任何其他值对应的键,否则您需要删除所有用户默认值意味着使用“removePersistentDomain”键。示例

让 appDomain = Bundle.main.bundleIdentifier!UserDefaults.standard.removePersistentDomain(forName: appDomain)


推荐阅读