1

I am trying to make a search function that queries user by their username from Firebase database, but I want my the function to only return the users with the exact username(letters) that is typed in to the search bar. so lets say if I type Mike into the search bar and tap search, I don't want it to return anything unless there is a user with this exact username(Mike).

I would really appreciate any help to improve my search function from you guys, thanks!

Here is my function:

 var REF_USERS = Database.database().reference().child("users") func searchQueryUsers(text: String, completion: @escaping (theUsers) -> Void) { REF_USERS.queryOrdered(byChild: "username").queryStarting(atValue: text).observeSingleEvent(of: .value, with: { snapshot in snapshot.children.forEach({ (sss) in let child = sss as! DataSnapshot if let dict = child.value as? [String: Any] { let user = theUsers.setUser(dict: dict, key: child.key) completion(user) } }) }) } 

1 Answer 1

2

Check this:

func searchQueryUsers(text: String, completion: @escaping (_ userNames: [String]) -> Void) { var userNames: [String] = [] REF_USERS.queryOrdered(byChild: "username").queryStarting(atValue: text).observeSingleEvent(of: .value, with: { snapshot in for item in snapshot.children { guard let item = item as? DataSnapshot else { break } //"name" is a key for name in FirebaseDatabese model if let dict = item.value as? [String: Any], let name = dict["name"] as? String { userNames.append(name) } } completion(userNames) }) } 

As a result, you will have a list of names.

But if you need only 1 name, use:

let nameOfFirstUser: String = userNames.first 

Why is it better to get the entire list of names?

In your database, for example, there may be such names: Mike, Michel ...

And if you enter "Mi" in the searchBar, both the first and the second name will match your search query.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help Maxwell, I will try this out.