Eliko Eliko - 4 months ago 38
Swift Question

Getting all the users same child in Firebase (Swift)

I am currently building an app in Firebase and I want to get all the users pineapple rate.

This is the tree:

user1: uid1 {
fruits: {
apple: 3
pineapple: 5
}
}

user2: uid2 {
fruits: {
apple: 4
pineapple: 2
}
}


I tried this code:

var ref = FIRDatabase.database().reference()
ref.queryOrderedByChild("fruits")
.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if ( snapshot.value is NSNull ) {
print("not found")
} else {
for child in snapshot.children {
let rate = child.value["pineapple"] as! String
print(rate)
}
}
})


But it gives me an error of unwrapping Nil.

Picture of the structre:

enter image description here

Answer

I suggest your structure should like this

enter image description here

than you just need to get children like

 for child in snapshot.children {
      if let fruits = child.value["fruits"] as? [String:String]{
          let rate = fruits["pineapple"]
           print(rate)
      }
 }

Edit:

with your structure

  var ref = FIRDatabase.database().reference()
     ref.queryOrderedByChild("user2")
        .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            if snapshot.exists() {
                for child in (snapshot.value?.allValues)! {
                    if let fruits = child["Fruits"] as? [String:String]{
                        let rate = fruits["pineapple"]
                        print(rate)
                    }
                }
            }
        })
Comments