我添加了用户通过 firebase 登录的可能性,效果很好。每次用户登录时,都会从实时数据库中读取数据并将其添加到应用程序中。
成功登录后,登录 View 将被关闭并更改为我的“MainViewController”。此“MainViewController”显示 startKm
和 currentKm
,但随着登录 View 被关闭,“MainViewController”中的数字不会更新 - 仅在 f.e. 之后再次更改 View 或关闭应用程序。
@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)
}
}
最佳答案
startKm = monthlyStartKmData
currentKm = currentKmData
这不会在您的 MainViewController 上分配变量,一旦您转向另一个 viewController,这些值就会消失。我不确定你如何在 viewController 之间进行更改,但使用 prepareForSegue
当您想在 viewController 之间传递值时很有帮助。
将此代码放入您的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 上可能调用其他 Segue,请将条件语句添加到 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
}
}
关于ios - Swift 和 Firebase - 登录后更新 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55974116/