gpt4 book ai didi

swift - 在类 init() 中使用 CLGeocoder

转载 作者:行者123 更新时间:2023-11-28 15:53:05 25 4
gpt4 key购买 nike

我想要一个能够使用CLGeocoder 获取国家/地区名称的。下面的代码不起作用可能是因为在 CLGeocoder 完成运行之前将变量 country 分配给了 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"

}
}

最佳答案

您所要做的就是将 self.country = country 移到完成处理程序中。数据是异步返回的,如果您在 country = placeholderself.country

上设置断点,您可以很好地看到这一点

您需要记住,当您在主视图 Controller 中定义 Place 的实例时,最初不会定义 place.country 的值。您可以在延迟后再次检查它以获取更新版本,或者您可以添加一个委托(delegate),以便它在值准备就绪时更新父 Controller

这是简单的版本

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
})
}
}

这是带有委托(delegate)的更优雅的版本

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)")
}

关于swift - 在类 init() 中使用 CLGeocoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com