首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在init()类中使用CLGeocoder

在init()类中使用CLGeocoder
EN

Stack Overflow用户
提问于 2017-02-08 03:25:30
回答 1查看 52关注 0票数 0

我想有一个能够使用CLGeocoder获得国家名称的class。下面的代码不能工作,可能是因为变量countryCLGeocoder结束运行之前被赋值给了self.country。我该怎么做才能让self.country真正从CLGeocoder获取国家名称

代码语言:javascript
复制
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"

    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-02-08 03:44:48

您所要做的就是将self.country = country移到完成处理程序中。数据是异步返回的,如果您在country = placeholderself.country行上设置断点,就可以很好地看到这一点

您需要记住,当您在主视图控制器中定义Place的实例时,place.country的值最初不会被定义。您可以在延迟一段时间后再次检查它以获取更新的版本,也可以添加一个委托,以便它在值就绪时更新父控制器

下面是简单的版本

代码语言:javascript
复制
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       
        })
    }
}

下面是带有委托的更优雅的版本

代码语言:javascript
复制
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中

代码语言:javascript
复制
class ViewController: UIViewController, CountryUpdatedDelegate {

    let place = Place(location: location!)
    place.delegate = self





func countryUpdated(_ country : String)
{
    print("Country has now been updated \(country)")
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42098258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档