Firebase retrieve data below auto ID In Swift

做~自己de王妃 提交于 2019-12-12 13:36:29

问题


I'm in trouble in retrieving data from Firebase.

I'd like to read all contactName data in JSON under auto ID , then append to UIPickerView.

Here is my JSON tree (used childByAutoId())

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.

How Can I fix it..?


回答1:


I solved myself!

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

And what I wanna do is to add data below auto ID.

I'm not sure this is good algorithm for solving this problem, But Anyway, I made it :)

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)
                        }
                    }
                })
            }
        }
    })


来源:https://stackoverflow.com/questions/44689303/firebase-retrieve-data-below-auto-id-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!