簡體   English   中英

如何從Firebase同步檢索數據?

[英]How to retrieve data synchronously from Firebase?

我有兩個集合,即用戶和問題。

基於使用userId登錄的用戶,我從users集合中檢索currQuestion值。

基於currQuestion值,我需要從Firebase Questions集合中檢索question文檔。

我用下面的代碼來檢索userId

rootRef.child("0").child("users")
        .queryOrderedByChild("userId")
        .queryEqualToValue("578ab1a0e9c2389b23a0e870")
        .observeSingleEventOfType(.Value, withBlock: { (snapshot) in

            for child in snapshot.children {
                self.currQuestion = child.value["currentQuestion"] as! Int
            }
            print("Current Question is \(self.currQuestion)")

            //print(snapshot.value as! Array<AnyObject>)
        }, withCancelBlock : { error in
                print(error.description)
        })

並找回問題

rootRef.child("0").child("questions")
.queryOrderedByChild("id")
.queryEqualToValue(currQuestion)
.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            for child in snapshot.children {
                print(child.value["question"] as! String)
            }

            }, withCancelBlock: { error in
                print(error.description)
        })

但是以上代碼是異步執行的。 我需要解決方案以使其同步或如何實現偵聽器,以便一旦currQuestion值更改currQuestion可以觸發問題查詢?

編寫您自己的方法,該方法將完成處理程序作為其參數,並等待該代碼塊完成。 像這樣:

 func someMethod(completion: (Bool) -> ()){
 rootRef.child("0").child("users")
    .queryOrderedByChild("userId")
    .queryEqualToValue("578ab1a0e9c2389b23a0e870")
    .observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        for child in snapshot.children {
            self.currQuestion = child.value["currentQuestion"] as! Int
        }
        print("Current Question is \(self.currQuestion)")
        completion(true)
        //print(snapshot.value as! Array<AnyObject>)
    }, withCancelBlock : { error in
            print(error.description)
    })
}

然后,每當您要調用該函數時,就這樣調用:

someMethod{ success in
if success{
//Here currValue is updated. Do what you want.
}
else{
//It is not updated and some error occurred. Do what you want.
}
}

完成處理程序通常用於等待代碼塊完全完成執行。 PS只要不阻塞主線程,就可以通過添加類似於上面所示代碼的完成處理程序來使異步請求執行同步操作。

它所做的只是先等待您的currValue更新(從服務器接收async數據),然后再按我所示的方式調用someMethod ,並且自從函數someMethod的最后一個也是唯一的參數是閉包(也稱為尾隨Closure ),則可以跳過括號並調用它。 是有關閉包的很好的閱讀。 並且由於閉包的類型為(Bool)->(),因此您只需在完成任務時告訴someMethod ,就像我的代碼中的completion(true)一樣,然后在調用它時success調用它(您可以可以根據需要使用,因為它是宣布像這樣,這將是 布爾類型中的任何字),然后在函數調用中使用它。 希望能幫助到你。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM