gpt4 book ai didi

swift - 如何异步使用 Firebase?数据库读取给出奇怪的结果

转载 作者:行者123 更新时间:2023-11-30 12:04:06 25 4
gpt4 key购买 nike

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

}

最佳答案

您将在 async 调用结束之前返回您的数组。您应该在异步调用中填充数组,然后调用另一个提供结果的方法。

static func SearchPostsByTags(tags: [String]) {
let dbref = FIRDatabase.database().reference().child("posts")
dbref.observeSingleEvent(of: .value, with: { snap in
let comps = snap.value as! [String : AnyObject]
var result = [Post]()
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)
}
}
}
}
}
// Call some func to deliver the finished result array
// You can also work with completion handlers - if you want to try have a look at callbacks / completion handler section of apples documentation
provideTheFinishedArr(result)
})
}

关于swift - 如何异步使用 Firebase?数据库读取给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com