Firebase / Swift:childSnapshotForPath访问autoID数据?

时间:2016-06-27 13:21:32

标签: firebase firebase-realtime-database snapshot

我目前正在努力访问存储在路径中的其他数据,更具体地说是来自子文件夹的数据。我的设置如下:

userID{
    username:Andreas,
    gender:Male,
    age:18,
    footballTeams{
       Team1{
           name:My team 1
           matchesPlayed:3
       }
    }
}

所以我目前正在运行此代码以获取用户名,性别和年龄:

ref.child("Users").observeEventType(.ChildAdded, withBlock: { (snapshot1:FIRDataSnapshot) in                   
      //code goes here..
      var username = String(snapshot1.value!["username"] as! String)
      var gender = String(snapshot1.value!["gender"] as! String)
      var age = Int(snapshot1.value!["age"] as! Int)                  
})

但是,我想抓住存储在footballTeams路径中的所有球队名称,命令如'Team1,Team2,Team3'等。所以我偶然发现了“snapshot1.childSnapshotForPath("footballTeams/Team1").value!["name"]”。但是,只要我知道每个团队名称路径的确切名称,这就行了,但这会存储为自动ID。关于我如何处理这个问题的任何想法?

提前致谢。

1 个答案:

答案 0 :(得分:2)

当您选择使用childSnapshotForPath时,您的选择正确。您只需获取/footballTeams分支快照并迭代它以获取每个孩子。

ref.child("Users").observeEventType(.ChildAdded, withBlock: { (snapshot1:FIRDataSnapshot) in                   
      var username = String(snapshot1.value!["username"] as! String)
      var gender = String(snapshot1.value!["gender"] as! String)
      var age = Int(snapshot1.value!["age"] as! Int)
      if let footballTeamsSnapshot = snapshot1.childSnapshotForPath("footballTeams") as? FIRDataSnapshot {
        for child in footballTeamsSnapshot.children.allObjects as [FDataSnapshot] {
            print(child.value)
        }
      }         
})