
[英]Load Another ViewController after Facebook Login with Swift
[英]Swift & Firebase - update ViewController after Login
我添加了用户通过firebase登录的可能性,这可以正常工作。 每次用户登录时,都会从实时数据库中读取数据并将其添加到应用程序中。
成功登录后,登录视图将被解除并更改为我的“MainViewController”。 这个“MainViewController”显示了startKm
和currentKm
,但是当登录视图被解除时, “MainViewController”中的数字不会被更新 - 只有在再次更改视图或关闭应用程序之后。
@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,这些值就会消失。 我不确定你是如何在viewControllers之间进行更改的,但是当你想在viewControllers之间传递值时,使用prepareForSegue
会很有帮助。
将此代码放在loginViewController中:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! MainViewController
destinationVC.startKm = monthlyStartKmData
destinationVC.currentKm = currentKmData
}
假设您已经currentKm' within
MainViewController中声明了变量startKm
和currentKm' within
,并且假设您正在从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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.