I wanted to make multiple API call in the same screen, but when one api fails other api should not be called? The below code is working fine. but what I need is , how can I refactor this in a more simpler way?
ApplicationService.requestAppEndPointUrl { success, error in
if success {
ApplicationService.appLinkDownload { success, error in
if success{
ApplicationService.requestApplicationSession { success, error in
if success {
ApplicationService.validateSdk { success, error in
if success {
ApplicationService.requestApplicationDetails { success, error in
if success{
print("Success")
}
else{
self.showErrorAlert(error)
}
}
}else{
self.showErrorAlert(error)
}
}
}else{
self.showErrorAlert(error)
}
}
}else{
self.showErrorAlert(error)
}
}
}else{
self.showErrorAlert(error)
}
}
3
Answers
Thats a pretty question. So if you don’t want to pass data from one api call to the other the solution is pretty easy.
All you have to do is to make a Service Manager that will manage all the service calls.
You can make an enum based on the services you want to call
Then you can make a class of the service
After that you will need to make the Service Manager
for this, you need to use OperationQueue & ** DispatchGroup** where you can make your API calls in BlockOperation and one operation depends on another, and their dispatch group helps you to hold the API calls.
I know code is a little bit nasty.
and if you are using swift 5.5 then use Async await mentioned by @Reinhard Männer
If
ApplicationService
is a class/struct that you can modify, you could convert the synchronous function calls with completion handler to asynchronous function calls, using Swift 5.5 concurrency. The code would look like:Then, the 1st error would break the call chain, would be cought and shown.
If you had to use the synchronous
ApplicationService
functions, you could convert them to asynchronous functions by using async wrappers as shown in the link cited above.