MKMapItem placemark is unavailable in swift

孤人 提交于 2019-12-21 19:38:09

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/27252319/mkmapitem-placemark-is-unavailable-in-swift

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