Swift 代码没有完成函数,它正在中途结束执行

Swift 代码没有完成函数,它正在中途结束执行,swift,firebase,firebase-realtime-database,Swift,Firebase,Firebase Realtime Database,我的代码如下: @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").observeSin

我的代码如下:

@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)
        }
    }

“在这里”会被打印出来,但布尔永远不会被打印出来,警报也会显示出来。为什么我的代码不输入if bool块并输出警报?

数据是从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)
    }
})
另见:

  • (显示具有自定义回调和委托的示例)
  • (显示如何使用调度组)
  • (另一个使用调度组的示例)

登录后导航到下一个视图控制器时,还必须将变量
bool
设置为false。这样,您可以再次登录,如果密码错误,则无法导航到下一页,只显示错误密码警报。

您正在调用
async
函数,在该函数中您正在更改
bool
值,但您正在该函数之外打印,您能检查是否正确吗?谢谢,这对于正确的密码有效,但当我输入错误的密码时,它仍然会将我带到下一页,并且我收到以下消息:
警告:尝试在已显示的上显示
。我该如何解决这个问题?