Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase get child ID swift ios

My Firebase looks like this. Bellow Active_Orders it appear childs with different names depending on their UID(user ID).

And this is my code to get the child's ID no matter what the name is. But it does not seem to work at all. Whats the proper way to get the child ID? Thanks

databaseRef.child("Active_Orders").observeEventType(FIRDataEventType.Value, withBlock: {
                    snapshot in
                //Get customerUID
                let customerUID = snapshot.value!.objectForKey("username") as! String
                self.setText("customerUID", value: customerUID)
like image 795
Victor Avatar asked Sep 26 '16 19:09

Victor


2 Answers

It is hard to tell from your question exactly what you are doing, but does this get you the list you need?

databaseRef.child("Active_Orders").observeEventOfType(.Value, withBlock: { (snapshot) in 
    if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
        for child in result {
            var orderID = child.key as! String
            print(orderID)
        }
    }
})

I believe this block should iterate over all the children that are inside "Active_Orders" and print out their key value (which seems to be what you are trying to print).

like image 195
Ryan Avatar answered Nov 08 '22 13:11

Ryan


For Swift 3 and Firebase 4

let ref = Database.database().reference()   

ref.child("Active_orders").observe(.value, with: { snapshot in

    if !snapshot.exists() {return} //may want to add better error handling here.

    let info = snapshot.value as! NSDictionary

    print("info keys are:", info.allKeys)
})
like image 33
ttorbik Avatar answered Nov 08 '22 13:11

ttorbik