gpt4 book ai didi

ios - 如何从 Firebase 同步检索数据?

转载 作者:搜寻专家 更新时间:2023-11-01 05:57:02 25 4
gpt4 key购买 nike

我有两个集合,即用户和问题。

根据使用 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 值更改后我可以返回问题查询?

最佳答案

编写您自己的方法,将完成处理程序作为其参数并等待该代码块完成。像这样:

 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.
}
}

完成处理程序通常用于等待代码块完全执行完毕。 P.S. 只要它们不阻塞主线程,异步请求就会通过添加完成处理程序(如上面所示的代码)来同步执行。

它只是等待您的 currValue 首先更新(从服务器接收数据 async),然后当您调用 someMethod 就像我展示的那样,因为函数 someMethod 的最后一个也是唯一的参数是一个闭包(又名 trailing Closure ),你可以跳过括号和叫它。 Here是一本关于闭包的好书。由于闭包是 (Bool) -> () 类型,您只需在任务完成时告诉您的 someMethod ,就像我的代码中的 completion(true) ,然后在调用它时,您可以使用 success (您可以使用任何您想要的词)调用它,WILL BE 类型为 Bool像这样声明,然后在函数调用中使用它。希望能帮助到你。 :)

关于ios - 如何从 Firebase 同步检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417312/

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