我希望class
能够使用CLGeocoder
获取国家/地区名称。下面的代码可能无效,因为在country
完成运行之前,变量self.country
已分配给CLGeocoder
。我该怎么办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"
}
}
答案 0 :(得分:1)
您需要做的就是在完成处理程序中移动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)")
}