gpt4 book ai didi

ios - 异步完成处理程序

转载 作者:行者123 更新时间:2023-11-30 13:56:50 26 4
gpt4 key购买 nike

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

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)")

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

The city: 

Here's the hood Toronto!

如何解决这个问题?

最佳答案

您应该将处理程序放在 block 内:

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 是异步的。一旦地理编码完成,完成 block 就会被调用,更有可能是在打印附加之后。

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

关于ios - 异步完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533235/

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