从CLGeocoder reverseGeocodeLocation返回无法返回的字符串 [英] Unable Return String from CLGeocoder reverseGeocodeLocation

查看:1214
本文介绍了从CLGeocoder reverseGeocodeLocation返回无法返回的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数来对位置进行反向地理编码,并将结果字符串分配给变量。遵循 this post i '有这样的:

I want to write a function to reverse geocode a location and assign the resulting string into a variable. Following this post i've got something like this:

extension CLLocation {

    func reverseGeocodeLocation(completion: (answer: String?) -> Void) {

        CLGeocoder().reverseGeocodeLocation(self) {

            if let error = $1 {
                print("[ERROR] \(error.localizedDescription)")
                return
            }

            if let a = $0?.last {
                guard let streetName = a.thoroughfare,
                    let postal = a.postalCode,
                    let city = a.locality else { return }

                completion(answer: "[\(streetName), \(postal) \(city)]")
            }

        }
    }
}

对于调用这个函数,我只有这样:

For calling this function i've just got something like this:

location.reverseGeocodeLocation { answer in
    print(answer)
}

字符串值 answer 到一个变量,我不知道如何将该数据传递出闭包。

But instead i want to assign the string value of answer to a variable and i don't know how to pass that data out of the closure. What is the best way to do something like this?

推荐答案

问题是它运行异步,所以你不能返回价值。如果你想更新一些属性或变量,正确的地方是在你提供给方法的闭包,例如:

The problem is that it runs asynchronously, so you can't return the value. If you want to update some property or variable, the right place to do that is in the closure you provide to the method, for example:

var geocodeString: String?

location.reverseGeocodeLocation { answer in
    geocodeString = answer
    // and trigger whatever UI or model update you want here
}

// but not here

闭包的全部目的完成处理程序模式是提供异步检索的数据的首选方式。

The entire purpose of the closure completion handler pattern is that is the preferred way to provide the data that was retrieved asynchronously.

这篇关于从CLGeocoder reverseGeocodeLocation返回无法返回的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆