Firebase/Swift: childSnapshotForPath access autoID data?

百般思念 提交于 2019-12-08 01:14:15

问题


I am currently struggling with accessing other data stored in a path, more specific the data from a sub-folder. My setup looks like this:

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

So I am currently running this code to grab both username, gender and age:

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

However, I want to grab all the team names stored in the footballTeams path, ordered like 'Team1, Team2, Team3' etc. So I stumbled upon "snapshot1.childSnapshotForPath("footballTeams/Team1").value!["name"]". However, this would have worked, as long as I knew the exact name of each team name-path, but this is stored as auto ID. Any ideas on how I would approach this?

Thanks in advance.


回答1:


You were on the right way when chose to work with childSnapshotForPath. You just have to get the /footballTeams branch snapshot and iterate over it to get each child.

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


来源:https://stackoverflow.com/questions/38055107/firebase-swift-childsnapshotforpath-access-autoid-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!