我正在尝试实现一个用户注册系统,我需要知道一个用户id(随机生成)是否已经分配给另一个用户。为此,我连接我的Firebase数据库并使用observer()方法检查生成的id的可用性。
但是,由于Firebase数据库查询是异步运行的,而且我只能在查询返回时知道结果,所以我无法在调用方法中使用正确的返回值。
我的方法是

repeat {
  id = generateUniqueId()
  check availability
} while (id is not unique)

我的实现是
var id:String
var test = true
repeat {
    id = generateId()
    ref.child("\(databaseReferenceName)").observe(.value) { (snapshot) in
        test = snapshot.hasChild("\(id)")
    }
} while (test == true)

即使test方法将false变量设置为hasChild(),此循环仍将继续运行。
如何更改代码以便能够捕获test变量的正确值?
我正在使用Swift 4.1
谢谢

最佳答案

由于进程是异步的,循环将一直运行到第一个test = false,但我认为您需要这种递归方式,直到找到可用的id

func checkID() {

       id = generateId()
       ref.child("\(databaseReferenceName)").observeSingleEvent(.value) { (snapshot) in
         let test = snapshot.hasChild("\(id)")

         if test {
           print("id exists")
           checkID() // check another one
         }
         else {
          print("this is the one \(id)")
         }
       }

}

另一件事是它应该是observeSingleEvent而不是observe

关于ios - Swift-在重复循环中使用闭包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52235408/

10-15 00:10
查看更多