1

I am sending two async calls at the same time and want to perform another task when getting result from both APIs...

One of the APIs is actually used to upload the video which can take time ... the task may complete even after the app comes from the background or maybe reopen after being terminated by the user (I re-upload the video if the last result was not successful)...

I want to perform some action when both APIs got successful results...

Previously I was using DispatchGroup() but I didn't find it a much effective solution since the app got crashed if you call group.leave() one extra time after calling group.enter(). User can check for the count before leaving the group with following line:

self.group.debugDescription.components(separatedBy: ",").filter({$0.contains("count")}).first!.components(separatedBy:CharacterSet.decimalDigits.inverted).filter({Int($0) != nil}) 

but this is overkill for such a small task that's why I am trying to find some better solution for such tasks.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Wahab Khan Jadon
  • 875
  • 13
  • 21

1 Answers1

3

you can use DispatchGroup, also check this link i hope it will solve your problem.

How to do two concurrent API calls in swift 4

func downloadDetails(){
let dispatchGroup = DispatchGroup()

dispatchGroup.enter()   // <<---
WebServiceManager.getAData(format:A, withCompletion: {(data: Any? , error: Error?) -> Void in

    if let success = data {

        DispatchQueue.main.async {
            (success code)
            dispatchGroup.leave()   // <<----
        }
    }
})

dispatchGroup.enter()   // <<---
webServiceManager.getBData(format: B, withCompletion: {(data: Any? , error: Error?) -> Void in

    if let success = data {

        DispatchQueue.main.async {
           (success code)
           dispatchGroup.leave()   // <<----
        }
    }
})

dispatchGroup.notify(queue: .main) {
    // whatever you want to do when both are done
}

}

Chandaboy
  • 1,302
  • 5
  • 10
  • I mention in the question that I used that but I don't find it a much effective solution... i have to put some extra conditions to prevent crash when using `DispatchQueue` – Wahab Khan Jadon Jul 03 '23 at 07:35