这是我的代码:
//从Firebase获取数据
func getData(withBlock completion:@escaping() ->Void){
let ref = Database.database().reference().child("hobbies")
let query = ref.queryOrdered(byChild: "cost").queryEqual(toValue: "low")
query.observe(.childAdded, with: {(snapshot) in
self.user_choice_Cost.append((snapshot.childSnapshot(forPath: "hobbyName").value as? String)!)
completion()
//print(self.user_choice_Cost)
})
{ (error) in
print(error)
}
//操作数据
getData{
let set2:Set<String> = ["a"]
let set1:Set<String> = Set(self.user_choice_Cost)
print(set1.union(set2))}
这可以正常工作!但是有什么方法可以让 user_choice_Cost 具有所有值([“a”,“b”])而不是一一([“a”],[“a”,“b”)]并操作 user_choice_Cost 数组而不将其放入 getData{} 内。因为如果我把它放在外面它只会返回“a”
最佳答案
当您观察 .childAdded
时,系统会为与您的查询匹配的每个子项调用您的完成处理程序。如果您只想为所有匹配的子项调用一次,您应该观察 .value
:
query.observe(.value, with: {(snapshot) in
由于您的完成处理程序仅被调用一次,因此本例中的快照包含所有匹配的节点。因此,您需要循环 snapshot.children
:
query.observe(.value, with: {(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value: String = (child.childSnapshot(forPath: "hobbyName").value as? String)!;
user_choice_Cost.append(value)
}
print("value \(user_choice_Cost)")
})
使用此代码,您只会看到一个日志输出,以及所有匹配的爱好名称。
关于ios - 从 Firebase 检索数据后对其进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46789388/