Swift version: 5.10
MapKit has built-in functionality to let us look up places and businesses around the world, all using natural language searches that can be passed in straight from user entry.
First, import the MapKit framework, then create an instance of MKLocalSearch.Request
that contains what you want to search for.
For example, this looks for Fortnum and Mason in London:
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = "Fortnum and Mason, London"
That provides no other information to Apple other than the text string, so it will look everywhere in the world for such a match.
If you wanted, you could provide a specific search region by letting the user pan around an MKMapView
for a specific location, then passing the region they are looking at to your search:
searchRequest.region = yourMapView.region
Once you’re ready, wrap the request inside an instance of MKLocalSearch
, like this:
let search = MKLocalSearch(request: searchRequest)
When you’re ready, call the start()
method on your search. This accepts one parameter, which is a closure that runs when the search completes – it will be handed the response data or an error, depending on what happened. This closure will always be run on your application’s main thread, so you can present some user interface immediately if you want.
As an example, this code will loop over all the results that were found for the search, printing out the phone number for each one:
search.start { response, error in
guard let response = response else {
print("Error: \(error?.localizedDescription ?? "Unknown error").")
return
}
for item in response.mapItems {
print(item.phoneNumber ?? "No phone number.")
}
}
Even without a map region, Apple Maps found the London store just fine, but obviously passing in a map region will help your accuracy improve.
If for some reason the request didn’t return quickly enough and you no longer need a response, call its cancel()
method to abort the request.
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 6.1
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.