2017-10-17 151 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)") 
    }) 

有了這個代碼,您只能看到一個日誌輸出,與所有愛好相匹配的名字。