我想有一个能够使用CLGeocoder获得国家名称的class。下面的代码不能工作,可能是因为变量country在CLGeocoder结束运行之前被赋值给了self.country。我该怎么做才能让self.country真正从CLGeocoder获取国家名称
class Place {
let location: CLLocation
let country: String
init(location: CLLocation) {
self.location = location
var country = ""
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, _) in
country = placemarks![0].country // I removed error and type checks for clarity
})
self.country = country // self.country = "", but should be for example "Canada"
}
}发布于 2017-02-08 03:44:48
您所要做的就是将self.country = country移到完成处理程序中。数据是异步返回的,如果您在country = placeholder和self.country行上设置断点,就可以很好地看到这一点
您需要记住,当您在主视图控制器中定义Place的实例时,place.country的值最初不会被定义。您可以在延迟一段时间后再次检查它以获取更新的版本,也可以添加一个委托,以便它在值就绪时更新父控制器
下面是简单的版本
class Place {
let location: CLLocation
var country: String = "Undefined"
init(location: CLLocation) {
self.location = location
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, _) in
self.country = placemarks![0].country! // I removed error and type checks for clarity
})
}
}下面是带有委托的更优雅的版本
protocol CountryUpdatedDelegate
{
func countryUpdated(_ country : String)
}
class Place {
let location: CLLocation
var country: String = "Undefined"
var delegate : CountryUpdatedDelegate!
init(location: CLLocation) {
self.location = location
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, _) in
guard let placeMarks = placemarks as [CLPlacemark]! else {
return
}
self.country = placemarks![0].country! // I removed error and type checks for clarity
self.delegate.countryUpdated(self.country)
})
}
}然后在你的ViewController中
class ViewController: UIViewController, CountryUpdatedDelegate {
let place = Place(location: location!)
place.delegate = self
func countryUpdated(_ country : String)
{
print("Country has now been updated \(country)")
}https://stackoverflow.com/questions/42098258
复制相似问题