1

How would you query Firebase to return children with names starting with a particular string?

I am trying to use Firebase with this autocomplete textfield project.

They use NSURLSession to fetch words that start with the letters that are being typed into the textfield:

private func handleTextFieldInterfaces(){
 autocompleteTextfield.onTextChange = {[weak self] text in
  self?.fetchAutocomplete(text)
 }
}

private func fetchAutocomplete(keyword:String) {
 dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
 if let data = data{
  do{
   let predictions = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
   var locations = [String]()
   for dict in predictions as! [NSDictionary]{
    locations.append(dict["description"] as! String)
   }
   dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.autocompleteTextfield.autoCompleteStrings = locations
   })
 })
 dataTask?.resume()
}

How could I do this with Firebase?

I think it's possible to use the isEqual to query exact matches but is there a starts with query?

ref = FIRDatabase.database().reference(withPath: "/locations")
exactLocations = ref.isEqual(keyword)
AL.
  • 35,361
  • 10
  • 135
  • 270
grabury
  • 4,267
  • 10
  • 55
  • 100
  • Is [this](https://github.com/mnbayan/AutocompleteTextfieldSwift) the project you are referring to? – Pat Needham Mar 03 '17 at 01:16
  • Yes thanks. Fixed my link. In their example code they use nsurlsession to get data from google places. I want to use my own Firebase data. – grabury Mar 03 '17 at 01:30

1 Answers1

2

You can query for strings starting with a specific substring with queryStartingAtValue and queryEndingAtValue.

ref.queryStarting(atValue: "value")
   .queryEnding(atValue: "value\\uf8ff")

See the Firebase documentation on sorting and filtering.

Also recommended:

Community
  • 1
  • 1
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734