过时:更新 UILabel 以显示当前位置
OUTDATED: Updating a UILabel to display current location
TLDR;
我想使用不同的函数获取主线程之外的位置,但我遇到了延迟。
详情:
我正在执行 GET 请求。稍后我解析 JSON 以在名为 'locationManager' 的方法中获取当前位置
现在我有一个 UILabel 出口,我想根据 JSON(反向地理编码)的结果一直更新到地图上显示的当前位置,但是如果我通过访问 label.text locationManager 我有一个延迟 + Xcode 告诉我它应该只通过主线程完成。
所以我尝试创建一个全局变量并在 locationManager 中更新它,但是当我访问 viewDidLoad() 中的 label.text 并将其提供给全局变量时,它保持为空(初始值)
有什么可能的解决方法?
var addrs = "" // the global variable
...
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Code
addrs = result.response.view[0].result[0].location.address.label
} .resume()
override func viewDidLoad() {
super.viewDidLoad()
locationLabel.text = ("Your Current Location Is :" + addrs)
}
注意:始终仅在主线程上更新您的 UI。使用以下代码解决您的问题。
DispatchQueue.main.async { [weak self] in
addrs = result.response.view[0].result[0].location.address.label
self?.locationLabel.text = ("Your Current Location Is :" + addrs)
}
TLDR;
我想使用不同的函数获取主线程之外的位置,但我遇到了延迟。
详情:
我正在执行 GET 请求。稍后我解析 JSON 以在名为 'locationManager' 的方法中获取当前位置 现在我有一个 UILabel 出口,我想根据 JSON(反向地理编码)的结果一直更新到地图上显示的当前位置,但是如果我通过访问 label.text locationManager 我有一个延迟 + Xcode 告诉我它应该只通过主线程完成。
所以我尝试创建一个全局变量并在 locationManager 中更新它,但是当我访问 viewDidLoad() 中的 label.text 并将其提供给全局变量时,它保持为空(初始值)
有什么可能的解决方法?
var addrs = "" // the global variable
...
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Code
addrs = result.response.view[0].result[0].location.address.label
} .resume()
override func viewDidLoad() {
super.viewDidLoad()
locationLabel.text = ("Your Current Location Is :" + addrs)
}
注意:始终仅在主线程上更新您的 UI。使用以下代码解决您的问题。
DispatchQueue.main.async { [weak self] in
addrs = result.response.view[0].result[0].location.address.label
self?.locationLabel.text = ("Your Current Location Is :" + addrs)
}