为什么我的快速代码出现故障?

时间:2019-06-02 22:41:04

标签: swift firebase firebase-realtime-database

我有以下代码,它似乎无法按顺序执行。

var theauth = 0
        ref = Database.database().reference()
        let usersRef = ref?.child("Users")
        let queryRef = usersRef?.queryOrdered(byChild: "username").queryEqual(toValue: emailTextField.text!)
        queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
            for snap in snapshot.children {
                let userSnap = snap as! DataSnapshot
                let thechild = userSnap.key
                print(thechild + "Hi")
                if thechild != ""{
                    theauth = 3
                    print(thechild + "1")
                }else if self.password2.text == self.passwordTextField.text{
                    theauth = 1
                }else{
                    theauth = 2}
            }
        })

        print(theauth)

输出的打印顺序与我预期的相反:

0 //theauth value
-Lf9xUh53VeL4OLlwqQoHi //thechild value + Hi
-Lf9xUh53VeL4OLlwqQo1  //thechild value + 1

想法?

1 个答案:

答案 0 :(得分:1)

查询是异步的,并且比结束时的打印语句运行时间更长。设置变量时,请考虑添加打印语句,或在查询完成后调用方法以执行该打印语句。

var theauth = 0
ref = Database.database().reference()
let usersRef = ref ? .child("Users")
let queryRef = usersRef ? .queryOrdered(byChild: "username").queryEqual(toValue: emailTextField.text!)
queryRef ? .observeSingleEvent( of: .value, with: {
  (snapshot) in
  for snap in snapshot.children {
    let userSnap = snap as!DataSnapshot
    let thechild = userSnap.key
    print(thechild + "Hi")
    if thechild != "" {
      theauth = 3
      print(thechild + "1")
    } else if self.password2.text == self.passwordTextField.text {
      theauth = 1
    } else {
      theauth = 2
    }
  }
  print(theauth)
})