user11682335
user11682335

Reputation:

Firebase snapshot to an array of objects

I'm new to Swift and Firebase and I'm building an app but I'm having a very difficult time (and it seems really simple as I'm getting the data printed out...) to convert the data (from Firebase Realtime Database) I retrieve to an array of users...

I would like to be able to do :

for user in users {
  print(user.name)
}

Output :

"Bob"
"John"
...

Basically having a simple array with objects inside.

This is how I retrieve my data :

let data = Database.database().reference().child("dbusers")
    
    data.child("users").observeSingleEvent(of: .value) { (snapshot) in
        print(snapshot)
    }

This is the output of the above print statement :

Snap (users) {
    0 =     {
        coeff1 = "";
        coeff2 = "";
        id = "";
        userLogo = "";
        userName = "";
        userUrl = " ";
    };
    1 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 1;
        userLogo = bobbyLogo;
        userName = Bob;
        userUrl = urlOfBobby;
    };
    2 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 2;
        userLogo = mariaLogo;
        userName = Maria;
        userUrl = urlOfMaria;
    };
    3 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 3;
        userLogo = johnLogo;
        userName = John;
        userUrl = urlOfJohn;
    };
    4 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 4;
        userLogo = jamesLogo;
        userName = James;
        userUrl = urlOfJames;
    };
    5 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 5;
        userLogo = jackLogo;
        userName = Jack;
        userUrl = urlOfJack;
    };
    6 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 6;
        userLogo = nikolasLogo;
        userName = Nikolas;
        userUrl = urlOfNikolas;
    };
}

Upvotes: 1

Views: 520

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

Since you're reading /dbusers/users, you get a snapshot that contains all users. You'll need to loop over the child nodes of the snapshot to get each individual user, and can then get their userName property.

Something like this:

let data = Database.database().reference().child("dbusers")    

data.child("users").observeSingleEvent(of: .value) { (snapshot) in
    for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
        print(childSnapshot.key) // prints the key of each user
        print(childSnapshot.childSnapshot(forPath:"userName").value) // prints the userName property
    }
}

Upvotes: 1

Related Questions