swift - 从异步完成处理程序获取数据

标签 swift asynchronous core-location

试图获取城市的名称,同时具有纬度和经度。 在模型类 Location 中,我正在使用 CLGeocoder(CoreLocation 的一部分)附带的 reverseGeocodeLocation(location: , completionHandler: ) 函数。

func getLocationName() {

    let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)

    geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
        guard let addressDict = placemarks?[0].addressDictionary else {
            return
        }

        if let city = addressDict["City"] as? String {
            self.currentCity = city
            print(city)
        }
        if let zip = addressDict["ZIP"] as? String {
            print(zip)
        }
        if let country = addressDict["Country"] as? String {
            print(country)
        }
    })
}

但是,在 ViewController 中,在运行 getLocationName() 之后,location.currentCitynil,因为完成处理程序是异步的,而且还没有完成。

如何确保完成处理程序已完成运行,以便我可以访问 location.currentCity

最佳答案

在你的 getLocationName 中传递一个闭包作为函数参数 您可以在 reverseGeocodeLocation 闭包内部调用。

func updateLocation(currentCity : String) -> Void
{
  print(currentCity)
}

func getLocationName(callback : @escaping (String) -> Void)
{

  let geoCoder = CLGeocoder()
  let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)

  geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
     guard let addressDict = placemarks?[0].addressDictionary else {
        return
     }


     if let city = addressDict["City"] as? String
     {
         self.currentCity = city
         callback(city)

         print(city)
      }
      if let zip = addressDict["ZIP"] as? String {
         print(zip)
      }
      if let country = addressDict["Country"] as? String {
        print(country)
      }
   })
 }

在您的 ViewController 中...

getLocationName(callback: updateLocation)

关于swift - 从异步完成处理程序获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236831/

相关文章:

swift - 在 ios 8/swift 中使用委托(delegate)的 AppLovin 集成

swift - Swift 中的 `nonisolated` 关键字是什么?

ios - 如何删除与另一个托管对象关联的托管对象

node.js - Node 在插入之前关闭数据库连接或根本不关闭

ios - NSLocationWhenInUseUsageDescription 错误一直显示

ios - 裁剪为圆形 cell.imageView?

c# - 任务状态一直等待激活

c# - 使用 `async` lambda 和 `Task.Run()` 是多余的吗?

ios - 使用 CLLocation 获取远处物体的路线

没有 WiFi 或 GPS 的 iOS 位置?