thenakulchawla
thenakulchawla

Reputation: 5254

Retrieving and filtering data in firebase

I am trying to filter some user data from firebase by usernames in swift 5, below is my code:

func getUsersWithUserName(givenUserName: String, completionHandler: @escaping (_ isSuccess: Bool) -> Void) {
        print("Enter getUsersWithUserName")
        print(givenUserName)
        let usersRef = dbRef.child("users")
        usersRef.queryOrdered(byChild: "userName").queryEqual(toValue: givenUserName, childKey: "userName").observeSingleEvent(of: .value, with: { snapshot in
            print("nakul")
            print(snapshot)
            for child in snapshot.children {
                print(child)
                let key = snapshot.key
                print(key)
            }
        })

        print("Exit getUsersWithUserName")

    }

Below is my firebase user node structure:

enter image description here

I have read the below answers already :

How to filter Firebase data in Swift?

querying firebase efficiently

but I am still not getting any results.

My log looks like below:

Enter searchBarButtonClicked
Enter getUsersWithUserName
nac
Exit getUsersWithUserName

I am not really sure what I am missing here.

Upvotes: 0

Views: 310

Answers (1)

Mohit Kumar
Mohit Kumar

Reputation: 3076

Please try this, hope this will solve your issue:

let query: DatabaseQuery = dbRef.child("users").queryOrdered(byChild: "userName").queryEqual(toValue: givenUserName)
query.observeSingleEvent(of: .value, with: { (snapshot) in
    //Your code here
}) { (error) in
    print(error.localizedDescription)
}

Please comment if you have any questions.

Happy to help!

Upvotes: 1

Related Questions