使用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块中触发。

任何build议不胜感激。

您可能会使用完成处理程序 。

 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... }