Skip to content

Instantly share code, notes, and snippets.

@fongd
Last active August 8, 2016 16:47
Show Gist options
  • Save fongd/e33eb4dcb9643fa2dc11e8b4fa2e6450 to your computer and use it in GitHub Desktop.
Save fongd/e33eb4dcb9643fa2dc11e8b4fa2e6450 to your computer and use it in GitHub Desktop.
Searches are getting executed out of order
class GooglePlacesSearchModel {
static var serialQueue: dispatch_queue_t = dispatch_queue_create("com.example.Search.GooglePlaces", DISPATCH_QUEUE_SERIAL)
[...]
func executeSearch(searchText: String, mapView: GMSMapView?, completion: ([AnyObject]) -> Void) -> () {
// get bounds of mapView to weight our autocomplete query accordingly
var bounds: GMSCoordinateBounds?
if let visibleRegion = mapView?.projection.visibleRegion() {
bounds = GMSCoordinateBounds(coordinate: visibleRegion.farLeft, coordinate: visibleRegion.nearRight)
}
// get centre point of our mapView for use with nearby search
if let centerCoordinates = getMapViewCenterCoordinate(mapView),
let radius = getViewRadius(mapView)
where shouldDoNearbySearch(searchText) {
dispatch_async(GooglePlacesSearchModel.serialQueue, {
self.doNearbySearch(searchText, location: centerCoordinates, radius: radius) { (results) in
// return [Dictionary<String, AnyObject>]
completion(results)
}
})
} else {
// autocomplete query
dispatch_async(GooglePlacesSearchModel.serialQueue, {
self.doAutocompleteQuery(searchText, bounds: bounds) { (results) in
// return [GMSAutocompletePrediction]
completion(results)
}
})
}
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
if let searchText = searchController.searchBar.text where searchText != "" {
// retrieve results from Google
self.googlePlacesSearchModel.executeSearch(searchText, mapView: self.mapView) { (completion) in
dispatch_async(dispatch_get_main_queue(), {
self.googlePlacesResults = completion
print("Search text was: \(searchText)")
print(completion)
let indexSection = NSIndexSet(index: tableSections.googlePlaces)
self.tableView.reloadData()
self.tableView.reloadSections(indexSection, withRowAnimation: .Automatic)
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment