在我的应用程序中,我使用 UserDefaults 来存储用户的登录状态(无论他们是否登录)和他们的用户名。它工作正常,因为当我登录、关闭应用程序并再次打开它时,我的应用程序会跳过登录页面并识别出我已经登录。不过,我现在正在尝试将注销按钮安装到单独的 viewController。单击时,此注销按钮需要 1.) 将 UserDefaults.loginStatus 重置为“False” 2.) 将 UserDefaults.username 重置为 nil 3.) 对登录页面执行 segue。
这是我的 ViewController.swift 文件中的相关代码。这是第一个控制 loginPage 的 viewController。
import UIKit
import Firebase
let defaults = UserDefaults.standard
class ViewController: UIViewController {
func DoLogin(username: String, password: String) {
//I Am not including a lot of the other stuff that takes place in this function, only the part that involves the defaults global variable
defaults.setValue(username, forKey: "username")
defaults.setValue("true", forKey: "loginStatus")
defaults.synchronize()
self.performSegue(withIdentifier: "loginToMain", sender: self) //This takes them to the main page of the app
}
override func viewDidLoad() {
super.viewDidLoad()
if let stringOne = defaults.string(forKey: "loginStatus") {
if stringOne == "true" { //If the user is logged in, proceed to main screen
DispatchQueue.main.async
{
self.performSegue(withIdentifier: "loginToMain", sender: self)
}
}
}
}
下面是我在 SecondViewController.swift 中的代码,特别是注销功能。
import UIKit
import Firebase
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let username = defaults.string(forKey: "username") {
checkAppSetup(username: username) //This is an unrelated function
//I included this because this works fine. Proving that I am able to read the defaults variable fine from this other viewController
}
}
@IBAction func logout(_ sender: Any) {
defaults.setValue("false", forKey: "username")
defaults.setValue("false", forKey: "loginStatus")
defaults.synchronize()
performSegue(withIdentifier: "logoutSegue", sender: nil)
}
当运行注销功能时,segue 执行正常,但默认值不会改变。有人可以解释为什么以及我可以做些什么来解决这个问题吗?
** 旁注,我实际上不会将默认值设置为“false”和“false”。在我调试此问题时,这只是暂时的。
最佳答案
几件事。
您应该使用 set(_:forKey:)
和 object(_:forKey
) 将键/值对读写为默认值,而不是 设置值(_:forKey)
。 (但是,您对 defaults.string(forKey: "loginStatus")
的使用是正确的。)
您可能应该将 nil 写入 userName 键:
defaults.set(nil, forKey: "username")
您的注销 IBAction
几乎肯定会将 loginStatus
设置为 false
,而不是 true
。
尝试改变这些东西。
此外,没有理由调用同步,除非您在 Xcode 中终止您的应用程序,而不是按下设备/模拟器上的主页按钮以让它正常退出。
关于ios - 从其他 viewController 访问 Swift 中的 UserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42610969/