在类init()中使用CLGeocoder

时间:2017-02-07 19:25:30

标签: swift class initialization clgeocoder

我希望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"

    }
}

1 个答案:

答案 0 :(得分:1)

您需要做的就是在完成处理程序中移动self.country = country。数据以异步方式返回,如果您在country = placeholderself.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)")
}
相关问题