【问题标题】:Completion handler asynchrony完成处理程序异步
【发布时间】:2015-11-04 22:24:00
【问题描述】:

我的完成处理程序有问题。这是一个带有完成处理程序的函数,位于实用程序文件中:

func convertGeopointToCity(geopoint: PFGeoPoint, complete: (city: String, error: NSError?) -> Void) {
    var city = ""
    let latitude = geopoint.latitude
    let longitude = geopoint.longitude
    let location: CLLocation = CLLocation(latitude: latitude, longitude: longitude)

    CLGeocoder().reverseGeocodeLocation(location, completionHandler: { placemarks, error in

        if (error == nil) {

            if let p = CLPlacemark?(placemarks![0]) {

                if let city = p.locality {
                    city = " \(city)!"
                    print("Here's the city:\(city)")
                    complete(city: city, error: nil)
                }
            }
        }
    })
}

我在 ViewController 中调用

    LocationUtility.instance.convertGeopointToCity(geopoint, complete: { result, error in
        if error != nil {
            print("error converting geopoint")
        } else {
            city = result as String
        }
    })
    print("The city: \(city)")

输出清楚地表明该函数在运行块之前没有等待完成:

The city: 

Here's the hood Toronto!

我该如何解决这个问题?

【问题讨论】:

  • 按预期工作。一旦工作完成,就会调用完成处理程序。当工作完成时,常规控制流继续 - 在你的情况下,这意味着打印语句被执行。

标签: ios swift


【解决方案1】:

你应该把你的处理程序放在块内:

LocationUtility.instance.convertGeopointToCity(geopoint, complete: { result, error in
    if error != nil {
        print("error converting geopoint")
    } else {
        city = result as String
        // do other stuff here, or call a method 
        print("The city: \(city)")
    }
})

CLGeocoder().reverseGeocodeLocation 是异步的。地理编码完成后立即调用完成块,更有可能在您的打印附加之后。

您应该在由完整块调用的另一个函数中执行操作,或者向块本身添加一些代码。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2019-01-13
    • 2012-08-10
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    相关资源
    最近更新 更多