Home > Back-end >  How to get value of nested branch in firebase swift
How to get value of nested branch in firebase swift

Time:02-13

I'm new to setting up firebase's realtime database, and I'm trying to access the content from a message to display in the app.

Here is how my database is structured:

.

I want to access "content" for each of the messages with the fewest value for "numberofresponses."

let ref: DatabaseReference! = Database.database().reference(withPath: "messagepool")
                    
ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
        print("no snapshot exists")
        return }
    print(snapshot)

The above code correctly prints the "messagepool," but I want the specific content value from each of the branches. I seem to be missing something. What is the correct way to do this? Thanks

CodePudding user response:

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So in your closure/completion handler you will need to loop over snapshot.children to get at the individual result snapshot(s):

ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
        print("no snapshot exists")
        return 
    }
    for childSnapshot in querySnapShot.children.allObjects as! [DataSnapshot] {
        print(childSnapshot.key)
        print(childSnapshot.value)
        guard let value = childSnapshot.value as? [String: Any] else { return }
        do {
          guard let content = value["content"] as? String,
          ...
        }
    }
}

Also see:

  • Related