Reputation: 5599
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)
Upvotes: 3
Views: 2617
Reputation: 599956
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:
Upvotes: 4