Write a post
Published Dec 02, 2015Last updated Feb 09, 2017

Swift Quick Tip: Using Apple MapKit's MKLocalSearch

Swift Quick Tip: Using Apple MapKit's MKLocalSearch

MKLocalSearch

Have you ever wondered which restaurants were nearby? Apple's MapKit framework provides an easy way to lookup places via natural language search.

MKLocalSearchRequest

First we start with a simple search request. You will need to specify the text for the natural language search and an optional region in which the search will take place. As an example we will specify a region from a MKMapView.

let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "Restaurants"
request.region = mapView.region

MKLocalSearchResponse

Next we make a MKLocalSearch from our request. We will get our search response from the completion block when calling the startWithCompletionHandler: method. In the block we get back an array of MKMapItem and an NSError. Each MKMapItem contains information about the location such as name, phone number, url, and address information via the CLPlacemark property.

let search = MKLocalSearch(request: request)
search.startWithCompletionHandler { response, error in
    guard let response = response else {
        print("There was an error searching for: \(request.naturalLanguageQuery) error: \(error)")
        return
    }

    for item in response.mapItems {
        // Display the received items
    }
}

Where To Go From Here?

Now that we have a new addition to your API tool belt you can add nearby location information in your apps. Check out Apple's MapKit Framework Reference to see other interesting things MapKit has to offer. Feel free to direct any questions toward me on Twitter @naturaln0va.

Discover and read more posts from Ryan Ackermann
get started
Enjoy this post?

Leave a like and comment for Ryan

1