Reputation: 389
My DB looks like this :
In my app, I have a search bar, at the time the user search I want to find all the users with the same name or starting with the same text.
So what I did was :
func seachUser(named : String){
usersRef.queryOrdered(byChild: "userName")
.queryStarting(atValue: named)
.observeSingleEvent(of: .value) { (snap) in
print(snap.value)
}
}
But, each time I get all the list of the users. How can I fix it? thanks
Upvotes: 1
Views: 3612
Reputation: 598847
Your querying for a so-called open-ended range. I.e. if named
is Jo
, then you'll get all results starting with Jone
and then every child node after that.
To only get user names starting with Jo
, you'll want to close the range by adding queryEnding(atValue:
. The trick here is to end at the last known character that you want, for which we typically use the highest known unicode character:
func seachUser(named : String){
usersRef.queryOrdered(byChild: "userName")
.queryStarting(atValue: named)
.queryEnding(atValue: named+"\uf8ff")
.observeSingleEvent(of: .value) { (snap) in
print(snap.value)
}
}
Upvotes: 1
Reputation: 2547
Try this may be helpful.
usersRef.child("users").queryOrdered(byChild: "userName").queryEqual(toValue: "userName like for ex Jone").observeSingleEvent(of: DataEventType.value) { (snapshot) in
if snapshot.value is NSNull {
return
}else{
for item in snapshot.children {
print(snapshot.value as! [String: AnyObject])
}
}
}
Upvotes: 0