我已经编写了以下函数来搜索我的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