gul josan
gul josan

Reputation: 33

Retrieve firebase data

Here is the firebase data tree enter image description here

There are two parents and each having two child each. How to retrieve all the data for "sex".

Here's is my code.

ref.child("Doctor").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for child in result {

                    print("Here 1")
                    print(child)
                    let gender = child.value!["sex"] as? String
                    print("Here 2")
                    //print("Sex")
                    print(gender)
                }

            } else {
                print("no results")
            }
        }) { (error) in
            print(error.localizedDescription)
        }

When I am printing the value of gender, it is showing nil value.

Upvotes: 1

Views: 588

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

You're trying to skip a level in your code. You listen to the value of the root node and then loop over its children. This gets you snapshots of the nodes Msm... and eqn.... If you check inside those nodes, neither of them has a child property sex.

To solve this, add one more loop in your code to get into the push IDs (the keys starting with -K):

ref.child("Doctor").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
            for child in result {
                for child2 in child.children {
                    let gender = child2.value!["sex"] as? String
                    print(gender)
                }
            }

        } else {
            print("no results")
        }
    }) { (error) in
        print(error.localizedDescription)
    }

Upvotes: 1

Related Questions