我的代码如下:
@IBAction func clicked(_ sender: Any) {
let ref = Database.database().reference()
let pass = password.text
var firpass = ""
var bool = false;
ref.child(name.text as! String).child("password").observeSingleEvent(of: .value, with: { dataSnapshot in
firpass = dataSnapshot.value as! String
if firpass == pass {
bool = true
print("in here")
}
})
print(bool)
if bool {
self.sendname = name.text!
let vc = DatabaseTableViewController(nibName: "DatabaseTableViewController", bundle: nil)
vc.finalName = self.sendname
navigationController?.pushViewController(vc, animated: true)
performSegue(withIdentifier: "username", sender: self)
} else {
let alert = UIAlertController(title: "Error", message: "Incorrect username or password", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
“in here”被打印,但 bool 从未被打印并且警报正在显示。为什么我的代码没有进入 if bool block 并输出警报?
最佳答案
数据是从 Firebase 异步加载的,因为这可能需要一段时间。不要让您的应用程序等待数据(这将是一个糟糕的用户体验),您的主代码会在加载数据时继续,然后一旦数据可用,您的闭包就会被调用。
这解释了您所看到的行为:当您的运行时,
尚未运行。
解决方案很简单,因为它最初令人困惑和烦人:任何需要数据库数据的代码都必须位于闭包内,或者从那里调用。
例如:
ref.child(name.text as! String).child("password").observeSingleEvent(of: .value, with: { dataSnapshot in
firpass = dataSnapshot.value as! String
if firpass == pass {
bool = true
print("in here")
}
print(bool)
if bool {
self.sendname = name.text!
let vc = DatabaseTableViewController(nibName: "DatabaseTableViewController", bundle: nil)
vc.finalName = self.sendname
navigationController?.pushViewController(vc, animated: true)
performSegue(withIdentifier: "username", sender: self)
} else {
let alert = UIAlertController(title: "Error", message: "Incorrect username or password", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
})
另请参阅:
- Firebase with Swift 3 counting the number of children
- Array of struct not updating outside the closure
- getting data out of a closure that retrieves data from firebase (显示带有自定义回调和委托(delegate)的示例)
- How to reload data after all Firebase calls finished? (展示如何使用调度组)
- Finish all asynchronous requests before loading data? (另一个使用调度组的示例)
关于swift - 代码未完成该功能,正在中途结束执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59710440/