first I want to say I'm new to the swift language.
My question almost mirrors this question: Accessing MKLocalSearchResponse item (swift)
However, when I apply this to my similar looking code I get an error "Value of type 'MKLocalSearch' has no member 'mapItems'"
Like in the link above I want the first mapItems (mapItems[0]) result. Can anybody help me?
Heres my code:
let latitude = String(currentLocation.coordinate.latitude)
let longitude = String(currentLocation.coordinate.longitude)
var station1Unwrapped: String! = ""
var station2Unwrapped: String! = ""
var coord: CLLocationCoordinate2D!
coord = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
var region: MKCoordinateRegion!
region = MKCoordinateRegion(center: coord, latitudinalMeters: 100, longitudinalMeters: 100);
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "Train Station"
request.region = region
let search = MKLocalSearch(request: request)
search.start { response, error in
guard let response = response else {
print("There was an error searching for: \(String(describing: request.naturalLanguageQuery)) error: \(String(describing: error))")
return
}
print("Inside function")
let station1 = response.mapItems[0].name
}
var newLocVar = (search.mapItems[0] as! MKMapItem).name
print(newLocVar)
The variable
searchisMKLocalSearch, so it doesn't has propertymapItems. If you want to print theMKMapItem's name, you should access themapItemsin the completion block, where you get access to theresponsewhich isMKLocalSearch.Response. The line you writelet station1 = response.mapItems[0].nameis perfectly correct and it contains the name of the firstmapItemsfound