Accessing MKLocalSearchResponse item (swift)

只谈情不闲聊 提交于 2019-12-29 09:58:05

问题


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


回答1:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!