0

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)
    }
}
Community
  • 1
  • 1
Jason
  • 808
  • 6
  • 25

1 Answers1

0

I couldn't present the results in the current view because the current view was not a table view. To present them without a table view I would have had to make a custom way to display them, and I realized it's simpler to just use a table view and pass a reference to that to the searchResultsController instead of passing nil

Jason
  • 808
  • 6
  • 25