gpt4 book ai didi

ios - swift - 如何完成任务

转载 作者:行者123 更新时间:2023-11-28 15:14:22 28 4
gpt4 key购买 nike

我正在尝试同时对多个位置进行反向地理编码。所以我创建了一个函数 performReverseGeoLocation。问题是,由于 CLGeocoder().reverseGeocodeLocation 是一个闭包,因此 completionHandlerLocations 将首先执行。我如何更改这些函数,以便调用者在 for 循环内的所有 CLGeocoder().reverseGeocodeLocation 完成后获得完成处理程序?

我试过的代码:

private func getImageLocation() {
performReverseGeoLocation(completionHandlerLocations: { (cities, countries) in
print("***** This is executed before the reverse geo code location is done")
})
}

private func performReverseGeoLocation(completionHandlerLocations: @escaping (_ cities: [String], _ countries: [String]) -> Void) {

var cities = [String]()
var countries = [String]()

for image in self.images {
let longitude = image.longitude
let latitude = image.latitude

let location = CLLocation(latitude: latitude, longitude: longitude)

CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
print("***** This is executed after completionHandlerLocations is done")
if error != nil {
self.alertError("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}

if placemarks!.count > 0 {
let pm = placemarks![0]

let country = pm.country
let city = pm.locality


if (!cities.contains(city!)) {
cities.append(city!)
}

if (!countries.contains(country!)) {
countries.append(country!)
}
}
else {
self.alertError("Fail to perform reverse geo location")
}
})
}
// THIS IS WILL EXECUTED FIRST
completionHandlerLocations(cities, countries)
}

最佳答案

你可以这样做:

var count = 0

for image in self.images {
...
CLGeocoder().reverseGeocodeLocation(location) {
// get result

counter ++

if count == self.images.count { // finish all requests
completionHandlerLocations(cities, countries)
}

}
}

这是最简单的方法。

关于ios - swift - 如何完成任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47129345/

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