2017-10-17 150 views
0

后取回呢?这里是我的代码:操作数据从火力地堡

//从火力地堡

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

这工作正常!但是没有什么办法可与所有值(“A”,“B”])得到user_choice_Cost而不是一个接一个地([“一”],[“一”,“B”)]和操纵user_choice_Cost阵列不用把它放在里面getData {}。因为如果我把外面只会返回“A”

+0

你为什么不为您的数据建立模型类? –

+0

这只是一个快速草案。如果我创建模型类更好吗?它会解决一个接一个的价值吗? –

回答

0

当你观察.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)") 
    }) 

有了这个代码,您只能看到一个日志输出,与所有爱好相匹配的名字。