來自Firebase數據庫的數據是異步讀取的。這意味着您的代碼執行的順序可能不是您所期望的。看到這種最簡單的方法是通過添加一些打印語句:
func fetchUidWithEmail (email: String) -> String {
print("Before starting query")
ref.child("userList").queryOrderedByChild("email").queryEqualToValue(email).observeEventType(.Value, withBlock: { (snapshot) in
print("In query callback block")
})
print("After starting query")
}
當你運行該代碼時,輸出爲:
開始查詢
開始查詢
之後之前查詢回調區塊
這是p可悲的不是你所期望的。但是它確實解釋了爲什麼返回uid不起作用:當您返回uid時,它尚未從Firebase加載。
解決此問題的方法是改變您對問題的看法。不要說「先取得uid,然後用uid做一些事情」,試着把它描述爲「每當我們拿到uid時,用它做點什麼」。
做到這一點的最簡單的方法是編寫需要的UID碼,進入加載數據的功能:
func fetchUidWithEmail (email: String) -> String {
ref.child("userList").queryOrderedByChild("email").queryEqualToValue(email).observeEventType(.Value, withBlock: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
print(snap.key)
// TODO: do anything you want with the uid here
}
}
})
}
雖然這工作,就意味着你可能有很多地方,你有通過電子郵件加載uid。更可重複使用的,如果你能在需要的UID給你的函數代碼傳遞:
fetchUidWithEmail("[email protected]") { (uid) in
print(uid)
}
這也正是火力地堡數據庫客戶端本身是如何工作的:
func fetchUidWithEmail (email: String, withBlock: String -> Void) -> Void {
ref.child("userList").queryOrderedByChild("email").queryEqualToValue(email).observeEventType(.Value, withBlock: { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
withBlock(snap.key)
}
}
})
}
然後你可以叫它:當你添加一個觀察者時,你傳入一個回調/塊。
非常感謝!我不知道這種功能。你幫了我一個大忙!再次感謝您的明確答案! – kindamark