gpt4 book ai didi

ios - 如何存储从reverseGeocodeLocation()方法(异步任务)检索的数据(到全局变量中)?

转载 作者:行者123 更新时间:2023-11-30 11:10:07 25 4
gpt4 key购买 nike

首先我有一个全局变量:

var userCity : String? 

使用reverseGeocodeLocation()从用户位置获取城市名称,我尝试将该城市名称信息存储到userCity全局变量中。我知道您不能简单地从异步任务返回数据。相反,你必须通过一个 block 传回。这是我在查看其他 StackOverflow 帖子后得到的信息:

//get user's location
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]

if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
locationManager.delegate = nil

reverseCoordinatesToCity(location: location) { (city) in
self.userCity = city
}
}
}

func reverseCoordinatesToCity(location: CLLocation, completion: @escaping (_ city: String?) -> Void) {

CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if (error != nil) {
print("Reverse geocoder failed with an error: " + (error?.localizedDescription)!)
completion("")
} else if (placemarks?.count)! > 0 {
let pm = placemarks![0] as CLPlacemark
completion(pm.locality!)
} else {
print("Problems with the data received from geocoder.")
completion("")
}
})
}

当我尝试以不同的方法打印 userCity 时。例如:

func someFunction() {
print(userCity!)
}

没有打印出任何内容,并且 userCity 似乎为零。我花了将近三个小时试图弄清楚这一点。我的主要目标是使用 segue 将这些数据传递到另一个 ViewController 上。

感谢任何帮助。谢谢。

最佳答案

正如 @rmaddy 所说,当 city 准备就绪时,您不会使用它。解决这个问题的方法是将 View Controller 逻辑与 CLGeocoder 回调连接起来。如果您不想再使用位置管理器,也值得将其设置为nil,因为stopUpdatingLocations()并不总是停止位置更新。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]

if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
locationManager = nil //this makes sure you don't get more updates

reverseCoordinatesToCity(location: location)
}
}

func reverseCoordinatesToCity(location: CLLocation) {

CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if (error != nil) {
print("Reverse geocoder failed with an error: " + (error?.localizedDescription)!)
} else if (placemarks?.count)! > 0 {
let pm = placemarks![0] as CLPlacemark
city = pm.locality!
//use city here with your view controllers
} else {
print("Problems with the data received from geocoder.")
}
})
}

关于ios - 如何存储从reverseGeocodeLocation()方法(异步任务)检索的数据(到全局变量中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267650/

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