Ad

How To Get Data For A Specific User Using Their Uid?

I would like to get data for a specific user, which I know its uid, I want to retrieve all the data that is for that specific user. Can you help me on how to retrieve the user data? Thank you in advance

func grabbingData() {
    let specificDatabase = Database.database().reference(withPath: "Data")
    let query = specificDatabase.queryOrdered(byChild: "uid").queryEqual(toValue: "ghD0lYZV1QOeJ2giUc3fNVxsLAV2")
    query.observeSingleEvent(of: .value, with: { (snapShot) in
        for child in snapShot.children {
            if let snap = child as? DataSnapshot {
                if let dictValues = snap.value as? [String: [String:String]] {
                    Array(dictValues.values).forEach {
                        let data = Data()
                        data.Name = $0["Name"]!
                        data.hold = $0["Data"]!
                        data.uid = $0["uid"]!
                        self.requestArray.append(data)
                    }
                    self.tableView.reloadData()
                }
            }
        }
    })
}

Firebase Structure

"Data" : {
    "ghD0lYZV1QOeJ2giUc3fNVxsLAV2" : {
        "-LlhLo-NJRn68ThFSAL2" : {
            "Name" : "Fake",
            "Data" : "data",
            "uid" : "ghD0lYZV1QOeJ2giUc3fNVxsLAV2"
        },
        "-Llc_-M2tU9bm-AqcTb5" : {
            "Name" : "Fake",
            "Data" : "data",
            "uid" : "ghD0lYZV1QOeJ2giUc3fNVxsLAV2"
        }
    }
},
Ad

Answer

The presented Firebase structure has some possibly unneeded duplication of the uid and it's unclear why but here's some code to read the structure in the question and print out the child values within each child node

func readUserNode() {
    let userNodeRef = self.ref.child("Data").child("ghD0lYZV1QOeJ2giUc3fNVxsLAV2")
    userNodeRef.observeSingleEvent(of: .value, with: { snapshot in
        let allChildNodes = snapshot.children.allObjects as! [DataSnapshot]
        for child in allChildNodes {
            let name = child.childSnapshot(forPath: "Name").value as? String ?? "no name"
            let data = child.childSnapshot(forPath: "Data").value  as? String ?? "no data"
            let uid = child.childSnapshot(forPath: "uid").value  as? String ?? "no uid"
            print(name, data, uid)
        }
    })
}

and the output (I changed Fake to Fake1 and Fake2 so you could see each node is printed)

Fake1 data ghD0lYZV1QOeJ2giUc3fNVxsLAV2
Fake2 data ghD0lYZV1QOeJ2giUc3fNVxsLAV2

To address the question further.

With Firebase you only need to query for data when you don't which nodes the data was stored in. In other words, for this use case, you know the users uid (ghD0lYZV1QOeJ2giUc3fNVxsLAV2) and the data you are after is stored in a node with that uid as the key.

Because of that, the node can be directly accessed without a query.

Ad
source: stackoverflow.com
Ad