使用 Firebase 同步观察 SingleEventOfType



我正在尝试使用信号量强制同步Firebase数据查询,以便我可以检查数据库中已有的项目。

这是我尝试检索快照并检查重复项的代码:

    let sem = dispatch_semaphore_create(0)
    self.firDB.child("sessions").observeSingleEventOfType(.Value, withBlock: { snapshot in
        snap = snapshot
        dispatch_semaphore_signal(sem)
    } )
    // semaphore is never asserted
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)
    var isDuplicate : Bool
    repeat {
        sID = genCode()
        isDuplicate =  snap.hasChild(sID)
    } while isDuplicate

在这种情况下,我需要在isDuplicate循环之前等待快照返回,但信号灯永远不会从observeSingleEventOfType块触发。

任何建议都非常感谢。

您可能会在使用

完成处理程序时感到不安。

func findUniqueId(completion:(uniqueId:String)->()) {
    self.firDB.child("sessions").observeSingleEventOfType(.Value, withBlock: { snapshot in
        var sID = self.genCode()
        while snapshot.hasChild(sID) {
            sID = self.genCode()
        }
        completion(uniqueId:sID)
    })
}

然后你会实现你所期望的

findUniqueId(){ (uniqueId:String) in
    // this will only be called when findUniqueId trigger completion(sID)...
    print(uniqueId)
    // proceed with you logic...
}

相关内容

  • 没有找到相关文章

最新更新