I’m going through the MapKit tutorials, and am straying a bit from the example app: I would like to implement an address search autocomplete drop-down, just like in the Apple Maps app.
I have most of the functionality working properly. Where I am struggling is getting the table of search results to work properly. I have implemented them using NSMenu, as I wanted them to look like the search results in the macOS Maps app. What is happening is that as soon as the autocompletion is performed, the NSMenu instance steals focus from the search bar, which I absolutely don’t want.
Should I be using a different approach? Here is my sample code:
private func printCoordinates(searchField: NSSearchField) {
let address = searchField.stringValue
// guard let selectedPlace = selectedPlace else { return }
geocoder.geocodeAddressString(address) {
[weak self] (placemarks, error) in
if let error = error {
print(error.localizedDescription)
return
}
guard let placemark = placemarks?.first else { return }
let menuPoint = NSPoint(x: searchField.frame.origin.x, y: searchField.frame.origin.y)
for placemark in placemarks! {
let menuItem = NSMenuItem()
var title: String = ""
if let city = placemark.locality, !city.isEmpty {
title = title + city
}
if let region = placemark.administrativeArea, !region.isEmpty {
title = title + ", " + region
}
if let coutry = placemark.country, !coutry.isEmpty {
title = title + ", " + coutry
}
guard nil == self!.searchResultsMenu.item(withTitle: title) else {
self?.searchResultsMenu.popUp(positioning: nil, at: menuPoint, in: self?.mapView)
return
}
menuItem.title = title
menuItem.representedObject = placemark
menuItem.action = #selector(self!.panAndZoomToTarget(menuItem:))
self?.searchResultsMenu.addItem(menuItem)
}
self?.searchResultsMenu.popUp(positioning: nil, at: menuPoint, in: self?.mapView)
}
}
Which object should I best use for the search results?
Any suggestions are welcome at this point.