user2423476
user2423476

Reputation: 2275

Swift Firebase get values in children

Im having issues receiving all posts using firebase for swift.

I want to loop through and get all imageURL values for all users that have made a post.

Post->userID->PostKey->imageURl

This is the code ive been trying to use to retrieve these values but to no avail.

var ref: DatabaseReference!

    ref = Database.database().reference()

    let postsRef = ref.child("posts")
    postsRef.observeSingleEvent(of: .value) { (snapshot) in
        if snapshot.exists() {
            for child in snapshot.children { //.value can return more than 1 match
                let snap = child as! DataSnapshot
                let dict = snap.value as! [String: Any]
                let myPostURL = dict["imageURL"] as! String
                print("POST URL: " + myPostURL)

            }

        } else {
            print("no user posts found")
        }
    }

enter image description here

Upvotes: 0

Views: 941

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598718

Your ref variable points to the posts node:

let postsRef = ref.child("posts")

Then you retrieve the value of that node, and loop over its children:

postsRef.observeSingleEvent(of: .value) { (snapshot) in
    if snapshot.exists() {
        for child in snapshot.children {

That means that child is a snapshot of xPCdfc5d...Oms2. You then get a dictionary of the properties of this child snapshot and print the imageURL property in there:

            let snap = child as! DataSnapshot
            let dict = snap.value as! [String: Any]
            let myPostURL = dict["imageURL"] as! String
            print("POST URL: " + myPostURL)

But if you follow along closely in your JSON, the xPCdfc5d...Oms2 node doesn't have a property imageURL.

You have two dynamic levels under posts, so you need two nested loops over the value:

postsRef.observeSingleEvent(of: .value) { (snapshot) in
    if snapshot.exists() {
        for userSnapshot in snapshot.children {              
            let userSnap = userSnapshot as! DataSnapshot
            for childSnapshot in userSnap.children {              
                let childSnap = childSnapshot as! DataSnapshot

                let dict = childSnap.value as! [String: Any]
                let myPostURL = dict["imageURL"] as! String
                print("POST URL: " + myPostURL)
            }
        }
    }
}

Upvotes: 2

Related Questions