当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - MKMapItem placemark is unavailable in swift

问题描述:

I am currently trying to make a searchbar that autopopulates with locations as the user types. I am using a MKLocalSearch to get a MKLocalSearchResponse and it appears to return values I can use. However to get the name, address or coordinates out of the search needs access to the MKPlacemark property in the search response. When I access the placemark I get the error:

'placemark' is unavailable: APIs deprecated as of iOS7 and earlier are unavailable in Swift

var request = MKLocalSearchRequest()

request.naturalLanguageQuery = searchText

//PUT HERE: check if network is on?

let localSearch: MKLocalSearch = MKLocalSearch(request: request)

localSearch.startWithCompletionHandler { (response: MKLocalSearchResponse!, error: NSError!) -> Void in

if (error == nil) {

println("searched")

for res in response.mapItems {

self.userSearch.append(res.placemark)

}

self.userSearch = response.mapItems.placemark

self.tableView?.reloadData()

} else {

println(error)

}

}

}

Does anyone know a workaround to accessing the placemark?

Thanks!

网友答案:

The response.mapItems array is declared in the API as of type [AnyObject]!.

The for loop isn't explicitly saying that res is of type MKMapItem (or that response.mapItems is actually [MKMapItem]).

So res is treated like an instance of AnyObject which isn't defined as having a placemark property.

This is why you get the compiler error 'placemark' is unavailable....


To fix this, cast res as an MKMapItem and then the placemark property will become visible.

Example:

for res in response.mapItems {
    if let mi = res as? MKMapItem {
        self.userSearch.append(mi.placemark)
    }
}



Also, this line after the for loop:

self.userSearch = response.mapItems.placemark

doesn't make sense if userSearch is supposed to be an array of placemarks.
The for loop is appending placemarks to that array and then this line is setting the array to a single placemark object (in addition, the mapItems object doesn't even have a placemark property).

This line should most likely be removed.

分享给朋友:
您可能感兴趣的文章:
随机阅读: