Run calls to a loop service

0

Hello, I have the following code:

for petition in petitions {
                    DispatchQueue.main.async {
                        EmailController.sharedInstance.sendPetitions(params: petition, completion: {
                            self.getPetitions()//Update the badge petitions
                        }, failure: { (errorCode, errorDescription) in

                        })
                    }

The problem is that of course the services are called one after the other even if they still have not received an answer, and what I want is precisely that they do not pass to the next item in the loop until the call of the service has not answered, Does anyone think of something? thanks

    
asked by Alejandro 14.12.2016 в 11:58
source

2 answers

0

You should have an array of requests and empty them as they are completed, at the same time you launch the next request.

var petitionsQueue: [Petition] = [] 

Set your request array in the way that best suits you. And then from where you want to start calls to the service call the following function:

func sendNextPetition() {
    if let nextPetition = self.petitionsQueue.first {
        EmailController.sharedInstance.sendPetitions(params: nextPetition, completion: {
        self.petitionsQueue.removeFirst()
        self.sendNextPetition()
        }, failure: { (errorCode, errorDescription) in

        })
    }
    else {
        print("todas las peticiones han sido procesadas")
    }
}
    
answered by 14.12.2016 / 19:21
source
0

This happens because your DispatchQueue is asynchronous, therefore it does it in the background, you can add

DispatchQueue.main.sync
    
answered by 14.12.2016 в 12:08