我试图同时为多个地点进行反向地理编码。所以我创建了一个函数a = [[1234,'1/8/2014'],[4123,'1/3/2014'],[5754,'1/12/2014'],[8548,'11/8/2014'],[9469,'11/9/2013'],[3564,'1/8/2013']]
data = {}
result = []
for item in a:
year = item[1].split('/')[-1]
data[year] = data.get(year, []) + [item[0]]
for key in data.keys():
items = data.get(key)
avg = sum(items)/len(items)
result.extend([key, avg])
print(result)
。问题是,自performReverseGeoLocation
封闭后,CLGeocoder().reverseGeocodeLocation
将首先执行。如何更改这些函数,以便在for循环中的所有completionHandlerLocations
完成后调用者将获得完成处理程序?
我尝试过的代码:
CLGeocoder().reverseGeocodeLocation
答案 0 :(得分:1)
您可以这样做:
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)
}
}
}
这是最简单的方法。
答案 1 :(得分:0)
如上所述 i-am-jorf ,您可以创建DispatchGroup并在所有反向地理编码任务完成后等待通知:
private func performReverseGeoLocation(completionHandlerLocations: @escaping (_ cities: [String], _ countries: [String]) -> Void) {
let group = DispatchGroup()
var cities = [String]()
var countries = [String]()
self.images.forEach { (location) in
group.enter()
let longitude = image.longitude
let latitude = image.latitude
let location = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemark, error) in
// do all your checks...
if placemark != nil && placemark!.count > 0 {
cities.append(placemark!.first!.locality!)
countries.append(placemark!.first!.country!)
}
group.leave()
})
}
group.notify(queue: DispatchQueue.main) {
completionHandlerLocations(cities, countries)
}
}