我已經編寫了以下函數來搜索我的Firebase數據庫,並且我還研究了使用調試語句並使用斷點進行測試以查看此函數正在提取正確的數據。但是當我最後返回數組時,數組是空的。據我瞭解,這是由於firebase的異步性質。在將數據添加到數組之前,函數即將結束。我如何解決這個問題,使其能夠按預期工作,我想返回一系列項目,然後我可以使用其他功能。如何異步使用Firebase?數據庫讀取給出奇怪的結果
static func SearchPostsByTags(tags: [String]) -> [Post]{
var result = [Post]()
let dbref = FIRDatabase.database().reference().child("posts")
dbref.observeSingleEvent(of: .value, with: { snap in
let comps = snap.value as! [String : AnyObject]
for(_, value) in comps {
let rawTags = value["tags"] as? NSArray
let compTags = rawTags as? [String]
if compTags != nil {
for cTag in compTags! {
for tag in tags {
if (tag == cTag) {
let foundPost = Post()
foundPost.postID = value["postID"] as! String
foundPost.title = value["title"] as! String
result.append(foundPost)
}
}
}
}
}
})
return result
}
}
尋找在迅速完成處理/回調,我認爲這將解決您的問題,您 – 3stud1ant3
不能達到你正在嘗試做的。最好的辦法是兩種方法。 Get和Set並且get方法將會有一個'completionHandler'。 – Torewin