2016-07-07 60 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