【发布时间】:2017-03-05 16:34:25
【问题描述】:
在我的应用程序中,我使用 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”。在我调试此问题时,这只是暂时的。
【问题讨论】:
-
这里
defaults.setValue("true", forKey: "loginStatus")你正在设置true。这是正确的吗?出于调试目的?我想应该是false -
是的,这是我问这个问题时的错字。在真正的代码中,它确实说“假”。谢谢你。但无论哪种方式,当我在 ViewController.swift 中访问它时,我在 SecondViewController 中设置的任何内容都不会出现
-
你能在
performSegue(withIdentifier: "logoutSegue", sender: nil)这一行设置断点并在控制台中输入这个:po UserDefaults.standard.value(forKey: "loginStatus"),看看它会返回什么true或false? -
我相信 Duncan C 在下面回答了我的问题,我只需要使用 .set(_ , forKey: "") 而不是 .setValue。但是谢谢你的想法!
标签: ios swift uiviewcontroller nsuserdefaults userdefaults