Ad

Why Do I Get All Users Data If I Just Needed One Specifically?

I am trying to get the Image url for a specific user but I end up getting it for both users that I just created randomly. All I need is one user ImageUrl, not both of them.

func retrieveTheImage() {

    let fullName = Database.database().reference(withPath: "User")
    fullName.queryOrdered(byChild: "uid").queryEqual(toValue: "ghD0lYZV1QOeJ2giUc3fNVxsLAV2")

    fullName.observeSingleEvent(of: .value) { (snapShot: DataSnapshot) in

        for child in snapShot.children {
            if let snap = child as? DataSnapshot {
                if let snapShotValue =  snap.value as? [String: String] {

                    let imageUrl = snapShotValue["ImageUrl"]!
                    print(imageUrl)


                    let storage = Storage.storage()
                    var reference: StorageReference!
                    reference = storage.reference(forURL: imageUrl)
                    reference.downloadURL { (url, error) in
                        let data = NSData(contentsOf: url!)
                        let image = UIImage(data: data! as Data )
                        self.pimageView.image = image
                    }
                }
            }
        }
    }
}

Firebase Structure

{
    "User" : {
        "Ncat5zlIHGQxRHEwGSX0vgspyE02" : {
            "FirstName" : "other",
            "ImageUrl" : "someUrl",
            "LastName" : "other",
            "uid" : "Ncat5zlIHGQxRHEwGSX0vgspyE02"
        },
        "ghD0lYZV1QOeJ2giUc3fNVxsLAV2" : {
            "FirstName" : "other",
            "ImageUrl" : "someUrl",
            "LastName" : "other",
            "uid" : "ghD0lYZV1QOeJ2giUc3fNVxsLAV2"
        }
    }
}
Ad

Answer

This line does nothing:

fullName.queryOrdered(byChild: "uid").queryEqual(toValue: "ghD0lYZV1QOeJ2giUc3fNVxsLAV2")

Calls to the query... APIs return a new Query object, so you'll need to hold on to that:

let fullName = Database.database().reference(withPath: "User")
let query = fullName.queryOrdered(byChild: "uid").queryEqual(toValue: "ghD0lYZV1QOeJ2giUc3fNVxsLAV2")

query.observeSingleEvent(of: .value) { (snapShot: DataSnapshot) in
Ad
source: stackoverflow.com
Ad