1

My DB looks like this :

enter image description here

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

Marry G
  • 377
  • 1
  • 3
  • 16

2 Answers2

1

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)
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Great, thanks! But there is still a problem, for example, if I want to search the name "Frank" and I send the string "rank" I get no result. how can I fix that? thanks – Marry G Feb 10 '18 at 17:21
  • That is a different search, which is not possible with the built-in operations of the Firebase Database. See https://stackoverflow.com/questions/28589092/firebase-query-find-item-with-child-that-contains-string – Frank van Puffelen Feb 11 '18 at 00:39
0

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])
    }
  }
}
Dixit Akabari
  • 2,419
  • 13
  • 26