2016-07-07 62 views
1

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

这是我试图获取一个快照,并检查重复的代码:

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块。

任何建议非常感谢。

+0

期待让我知道如果u取得任何进展 – adolfosrs

+0

感谢@adolfosrs,那绝对是比我试图做一个清洁的解决方案,并现在我已经开始工作了,只需对代码进行少量修改即可。我仍然不确定为什么我的信号量不起作用,但是我会去阅读其他一些线索,试图弄清楚我做错了什么。 – djruss70

回答

3

您可能会使用completion handler

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

这对我来说很方便,谢谢 – RJH