我为用户添加了通过Firebase登录的可能性,该方法工作正常。每次用户登录时,都会从实时数据库读取数据并将其添加到应用程序。
在成功登录后,登录视图将被关闭,并更改为我的“ MainViewController”。此“ MainViewController”显示startKm
和currentKm
,但是由于关闭了登录视图,“ MainViewController”中的数字不会更新-仅在f.e之后。再次更改视图或关闭应用程序。
@IBAction func login(_ sender: Any) {
guard let email = emailInput.text else { return }
guard let password = passwordInput.text else { return }
Auth.auth().signIn(withEmail: email, password: password) { user, error in
if error == nil && user != nil {
self.readData()
self.dismiss(animated: false, completion: nil)
} else {
print("Error logging in: ", error!.localizedDescription)
let alert = UIAlertController(title: "Fehler beim Einloggen", message: error!.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Verstanden", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
func readData() {
guard let uid = Auth.auth().currentUser?.uid else { return }
let databaseRef = Database.database().reference()
databaseRef.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let monthlyStartKmData = value?["monthlyStartKm"] as? Int ?? 0
let currentKmData = value?["currentKm"] as? Int ?? 0
...
startKm = monthlyStartKmData
currentKm = currentKmData
...
}) { (error) in
print(error.localizedDescription)
}
}
答案 0 :(得分:0)
startKm = monthlyStartKmData
currentKm = currentKmData
这不会在MainViewController上分配变量,一旦您将其设置为另一个viewController,这些值将消失。我不确定您如何在viewControllers之间进行更改,但是当您想在viewControllers之间传递值时,使用prepareForSegue
会很有帮助。
将此代码放在您的loginViewController中:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! MainViewController
destinationVC.startKm = monthlyStartKmData
destinationVC.currentKm = currentKmData
}
这应该可行,假设您已经声明了变量startKm
和currentKm' within
MainViewController`,并假设您正在从logInVC切换到MainViewController。
如果有可能在logInVC上调用其他命令,请在prepareForSegue
调用中添加条件语句,例如:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MainViewControllerSegue" { //or whatever you call the segue
let destinationVC = segue.destination as! MainViewController
destinationVC.startKm = monthlyStartKmData
destinationVC.currentKm = currentKmData
}
}