Eliko
Eliko

Reputation: 1137

Get information no matter number of childs in Firebase (Swift)

This is my tree:

enter image description here

I want to get the d value ("its d")

But I do not get any information printed

ref.queryOrderedByChild("userA")
            .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                if snapshot.exists() {
                    for child in (snapshot.value?.allValues)! {
                        if let fruits = child["c"] as? [String:String]{
                            let name = fruits["d"]
                            print(name)
                            }
                    }

Upvotes: 1

Views: 95

Answers (2)

Jay
Jay

Reputation: 35648

This is the answer to specific question:

Get information no matter number of childs in Firebase

not sure if it's what you are looking for however.

To get to 'd', you don't need a query. You can directly access that data.

Here's my structure (matching yours)

"the_users" : {
    "a" : {
      "b" : {
        "c" : {
          "d" : "It's d"
        }
      }
    }
  }

and the code to get to the 'd' value

let theUsersRef = rootRef.child("the_users")
let dRef = theUsersRef.child("a/b/c/d")
dRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
     let msg = snapshot.value as! String
     print(msg)
})

and the output

It's d

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598718

When you call queryOrderedByChild("userA"), it tells the database to order by the primitive value of the userA property. Since in your JSON there is no userA property with a primitive value, the order by statement is meaningless.

You don't filter the data in the query, so you will get a snapshot with all data at the location where you attach the listener. It's unclear from your code sample what location that is, but it's very likely that it's higher in the JSON tree than where a child c exists. So that means that you're not printing any name.

It would probably a lot clearer if you simple print all children:

ref.queryOrderedByChild("userA")
   .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
       if snapshot.exists() {
           for child in (snapshot.value?.allValues)! {
               print(child.key)
               if let fruits = child["c"] as? [String:String]{
                   let name = fruits["d"]
                   print(name)
               }
           }
       }
   })

Upvotes: 0

Related Questions