swift - 代码未完成该功能,正在中途结束执行

标签 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").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)
    }
})

另请参阅:

关于swift - 代码未完成该功能,正在中途结束执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59710440/

相关文章:

swift - swift 中的 '()' 类型是什么?

ios - 基本 Firebase 数据库问题 (Xcode + Swift)

swift - 为什么我不在我的 firebase 数据库中的特定位置检索值并且只得到 nil?

ios - Swift 中的字符串格式化

ios - 如何从父 View 中删除 uiview?

swift - 返回没有 child 的结果的 child 的 Firebase 订单

ios - 当我运行我的应用程序时,我收到此错误。线程 1 : Fatal error: Unexpectedly found nil while unwrapping an Optional value

android - 使用身份验证拒绝 Firebase 权限(读取和写入)

javascript - react 函数不返回任何值

ios - UI图像方向问题