When I do println(localSearchResponse)
, I get a MapItem object, which includes a ton of details about the location. In this example, its UCSD. Here is the output showing in my log.
<MKLocalSearchResponse: 0x1c53d640> {
boundingRegion = "<center:+32.87514836, -117.23958822 span:+0.00725621, +0.00825332>";
mapItems = (
"<MKMapItem: 0x1c538090> {\n isCurrentLocation = 0;\n name = \"University of California, San Diego\";\n phoneNumber = \"+18585342230\";\n placemark = \"University of California, San Diego, 9500 Gilman Dr, La Jolla, CA 92093-5004, United States @ <+32.87529400,-117.23961000> +/- 0.00m, region CLCircularRegion (identifier:'<+32.87514837,-117.23958825> radius 557.57', center:<+32.87514837,-117.23958825>, radius:557.57m)\";\n url = \"http://www.ucsd.edu\";\n}"
);
}
Notice how it outputs placemark = University of California...
and has the address? How do I get this value and store it into a variable? Here is my code:
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = addressTextField.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
var alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again")
alert.show()
return
}
//prints the MKLocalSearchResponse with name, phoneNumber, placemark
println(localSearchResponse)
//Get latitude and longitude
var newRecordLat = localSearchResponse.boundingRegion.center.latitude
var newRecordLong = localSearchResponse.boundingRegion.center.longitude
//How do I get the address, which is "placemark" in the MKLocalSearchResponse?
var newRecordAddress = localSearchResponse.mapItems...???
//store values to Parse
self.latToParse = newRecordLat
self.longToParse = newRecordLong
}
Here is the documentation of MKSearchResponse
And here is the documentation of MKMapItem
The answer is:
var newRecordAddress = (localSearchResponse.mapItems[0] as! MKMapItem).placemark
This object contains all information you need. Checked it in demo project
Address only:
var newRecordAddress = (localSearchResponse.mapItems[0] as! MKMapItem).placemark
let addressOnly = newRecordAddress.name + ", " + newRecordAddress.title
newRecordAddress.name
is place's name
newRecordAddress.title
is place's address you required
Because mapItems
is an array, you need to call first
to access the first element of that array. This will return an MKMapItem
, so you can get the placemark property with this code:
localSearchResponse.mapItems.first.placemark
来源:https://stackoverflow.com/questions/31488686/accessing-mklocalsearchresponse-item-swift