I\'m using GCD to notify main thread (have 2 async calls inside the function)
My code:
func getWavesByMostRecent(closure: @escaping ([Wave]?) -> Void)
Try this change:
self.geoFire?.getLocationForKey(wave.waveID, withCallback: { (location, error) in
defer { dispatchGroup.leave() }
guard let location = location else { return }
if error == nil {
if location.distance(from: currentLocation) < Constants.distance {
print("Wave", wave.waveID, "is in range")
waves.append(wave)
} else {
print("Wave", wave.waveID, "is out of range")
}
} else {
print(error?.localizedDescription ?? "")
}
})
As noted in matt's comment defer
is a good tool to do something always when leaving.
This is another issue, but updating an Array from multiple thread simultaneously would cause some problems. It rarely happens, so it can be a hard-to-fix bug.
I'm not sure if GeoFire
calls its callback in the main thread or not, but if not, you should better enclose all the callback code in DispatchQueue.main.async {...}
.