I have a method with a completion handler
func postLandGradingImages(cellHolder: Array<ImagesData>, completionHandler:@escaping (_ result:Bool) -> Void) {
//Define bool for returning data
var returnedResults = false
//Call API
WebService().postLandGradingImages(cellHolder)
{
(result: Bool) in
DispatchQueue.main.async {
//Return our results
returnedResults = result
completionHandler(returnedResults)
}
}
}
and I am calling this method inside a loop like so:
for asset: PHAsset in photoAssets
{
self.postLandGradingImages(cellHolder: [ImagesData(jobNo: self.JobNo, ImageBytes: imageStr)]) { result in
}
}
What I am trying to do is if this fails at some point, display an alert and stop looping and after the loop is done and all my calls returned true display an alert at the end.
This is what I have tried:
var returned = false
for asset: PHAsset in photoAssets
{
imageManager.requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFill, options: options, resultHandler: { (image, info) in
let imageData:Data = UIImagePNGRepresentation(image!)!
let imageStr = imageData.base64EncodedString()
self.postLandGradingImages(cellHolder: [ImagesData(jobNo: self.JobNo, ImageBytes: imageStr)]) { result in
returned = result
if(returned == false)
{
self.customAlert(title: "Error", message: "There was an error when saving data, please try again later.")
}
}
})
}
if(returned == true)
{
self.customAlert(title: "Error", message: “All Good“)
}
But my alert saying All Good never comes up as returned gets checked before even my first call. What am I doing wrong and how do I accomplish what I am trying to accomplish?