Firebase Fetch Data Under Auto ID In Swift

I am having problems fetching data from Firebase.

I would like to read all contactName data into JSON in auto id and then add to UIPickerView.

Here is my JSON tree (used by childByAutoId ()) enter image description here

And here is my Swift Code

dbRef = Database.database().reference()

dbRef.child("user").child("contacts").queryOrdered(byChild: "contactName").observeSingleEvent(of: .value, with: {(snapshot) in

    for snap in snapshot.children {

        let userSnap = snap as! DataSnapshot

        let contactName = userSnap.value as? String

            self.pickOption.append("\(contactName)")
        }
    })

      

But the result shows me all nil data ... looks like this.

enter image description here

How can I fix this ..?

+3


source to share


1 answer


I decided it myself!

But first of all, I decided not to use UIPickerView.

And I want to do this to add data below auto id.



I'm not sure if this is a good algorithm for solving this problem, but I did it anyway :)

dbRef.child("user/contacts/").observe(.value, with: {(snapshot) in

    if let result = snapshot.children.allObjects as? [DataSnapshot] {

            for child in result {

                let orderID = child.key as String //get autoID

                self.dbRef.child("user/contacts/\(orderID)/contactName").observe(.value, with: { (snapshot) in

                    if let nameDB = snapshot.value as? String {

                        if self.debtorName == nameDB {

                            self.dbRef.child("user/contacts/\(orderID)").updateChildValues(data)
                        }
                    }
                })
            }
        }
    })

      

+2


source







All Articles