Skip to content

Instantly share code, notes, and snippets.

@satan87
Last active December 14, 2021 17:47
Show Gist options
  • Save satan87/d860adb40797400074ea83cd5bc9c567 to your computer and use it in GitHub Desktop.
Save satan87/d860adb40797400074ea83cd5bc9c567 to your computer and use it in GitHub Desktop.
import Foundation
import MapKit
final class MapKitService {
// Map the Apple Category to your own category
private let typesToDrink: [MKPointOfInterestCategory] = [.brewery, .cafe, .winery]
private let typesToEat: [MKPointOfInterestCategory] = [.foodMarket, .restaurant]
func retrieve(from: String, completionBlock: @escaping ([Place]) -> Void) {
var places = [Place]()
// Create the request
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = from
// Define what you want in the result
request.resultTypes.insert(.address)
request.resultTypes.insert(.pointOfInterest)
// Add a filter on the Category of the place
var allTypes = typesToDrink
allTypes.append(contentsOf: typesToEat)
let filter = MKPointOfInterestFilter(including: allTypes)
request.pointOfInterestFilter = filter
// Create the search
let search = MKLocalSearch(request: request)
// Launch the request
search.start { response, error in
guard let response = response else {
if let error = error {
print("\(error.localizedDescription)")
}
return
}
//Answers
for item in response.mapItems {
if let name = item.name {
var place = Place()
place.name = name
//Webiste
if let website = item.url {
place.url = website.absoluteString
}
//Address
var address = Address()
address.street = item.placemark.thoroughfare.orEmpty
// ... Handle the rest of the address
place.addresses.append(address)
places.append(place)
}
}
completionBlock(places)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment