Ace
Ace

Reputation: 613

Swift firebase query nested child nodes

I have the following set up in firebase: enter image description here

I then query the firebase:

func getUserInfo(){

var tempUsers = [user]()
           // query for the data 
        let itemRef = Database.database().reference(fromURL: "[url]").child("users")
        itemRef.observe(.value, with: { snapshot in

            for child in snapshot.children {

        if let childSnapshot = child as? DataSnapshot,
            let dict = childSnapshot.value as? [String: Any], 
            let sport = dict["Sport"] as? String, 
            let username = dict["username"] as? String{

                let user = user(sport: sport, username: username)

                tempUsers.append(user)
            }
         }
             self.usersArray = tempUsers                           

        }){ (error) in
            print("the error is: \(error.localizedDescription)")
        }
  }

Users:

    class user {

            var username: String 
            var sport: String
            var teamInfo: [teamInfo]


      init(username: String, sport: String, teamInfo: [teamInfo])
  {
    self.username = username
    self.sport = sport
    self.teamInfo = [teamInfo]

  }
}

struct teamInfo {
  var AwayTeam: String
  var HomeTeam = String
  var Jersey = Int

}

I would like to know how would I be able to get the Team information within my query and then be able to add it to the instance of User, I have tried to make "Team" into a dict but this does not give me the intended result.

Upvotes: 0

Views: 188

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598708

First things first: you have an inconsistency in username. Your JSON spells it Username with an uppercase U, while the code uses username with a lowercase u. Since Firebase is case-sensitive, your code will right now never get the correct value.

Aside from that, you can get the values from the nested children by using DataSnapshot.childSnapshot(forPath:).

itemRef.observe(.value, with: { snapshot in
    for child in snapshot.children {

    if let childSnapshot = child as? DataSnapshot,
        let dict = childSnapshot.value as? [String: Any], 
        let team = childSnapshot.childSnapshot(forPath: "Team/AwayTeam").value as? String;

Upvotes: 1

Related Questions