I'm looking to implement search completion in a map page using native iOS features. I've found this answer which helped
However, they give their results to a tableview. I want to present the results in the same view as the map. I'm also wondering how to see which completion the user selects
Here's all the relevant code I have now
// Enable Searching
var searchController: UISearchController!
var request: MKLocalSearchRequest!
var search: MKLocalSearch!
var response: MKLocalSearchResponse!
// Autocompletion
var searchCompleter = MKLocalSearchCompleter()
var searchResults = [MKLocalSearchCompletion]()
override func viewDidLoad() {
searchCompleter.delegate = self
searchCompleter.filterType = MKSearchCompletionFilterType.LocationsOnly
super.viewDidLoad()
}
@IBAction func searchAction(sender: UIBarButtonItem) {
searchController = UISearchController(searchResultsController: nil) // nil as I want the autocompletion results to appear in this view
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
presentViewController(searchController, animated: true, completion: nil)
}
func completerDidUpdateResults(completer: MKLocalSearchCompleter) {
searchResults = completer.results
print(searchResults) // Shows me that this is working and that it is grabbing locations
// I need to instead give these results to the UISearchController to display
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
searchCompleter.queryFragment = searchBar.text!
}
func searchBarSearchButtonClicked(searchBar: UISearchBar){
searchBar.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
//request = MKLocalSearchRequest(completion: /* user's completion selection*/)
//Since I don't know the above, it currently just searches by user text
request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchBar.text
search = MKLocalSearch(request: request)
search.startWithCompletionHandler {
(response, error) -> Void in
if response == nil{
return
}
self.map.centerCoordinate = CLLocationCoordinate2D(latitude: response!.boundingRegion.center.latitude, longitude: response!.boundingRegion.center.longitude)
}
}