当我执行println(localSearchResponse)
时,我得到一个MapItem对象,其中包含大量关于位置的详细信息。在这个例子中,它是UCSD。以下是我的日志中显示的输出。
<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}"
);
}
注意它是如何输出placemark = University of California...
和地址的?我如何获得这个值并将其存储到一个变量中?下面是我的代码:
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
}
这是MKSearchResponse的文档
这里是MKMapItem的文档
答案是:
var newRecordAddress = (localSearchResponse.mapItems[0] as! MKMapItem).placemark
该对象包含您需要的所有信息。在demo项目中检查
只地址:
var newRecordAddress = (localSearchResponse.mapItems[0] as! MKMapItem).placemark
let addressOnly = newRecordAddress.name + ", " + newRecordAddress.title
newRecordAddress.name
为地名newRecordAddress.title
是您需要的地址
因为mapItems
是一个数组,所以需要调用first
来访问该数组的第一个元素。这将返回一个MKMapItem
,因此您可以使用以下代码获得placemark属性:
localSearchResponse.mapItems.first.placemark