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 search
is MKLocalSearch
, so it doesn't has property mapItems
. If you want to print the MKMapItem's name
, you should access the mapItems
in the completion block, where you get access to the response
which is MKLocalSearch.Response
. The line you write let station1 = response.mapItems[0].name
is perfectly correct and it contains the name of the first mapItems
found