Search code examples
iosswifturlsession

How to make multiple Network calls and send result altogether after success only?


I want to make two network calls and want to send result back to viewcontroller only when both the calls successfully completes. In following code I have used booleans gotCountries & gotOcceans to know if I got response. I want to remove these boolean flags and make sure I am sending both the result using completion block.

func fetchCountries() {
    countries = Network call to get countries success
    gotCountries = true // Boolean
    if gotCountries && gotOcceans {
        onCompletion?(self.countries, self.occeans)
    }
}

func fetchOcceans() {
    occeans = Network call to get occeans success
    gotOcceans = true // Boolean
    if gotCountries && gotOcceans {
        onCompletion?(self.countries, self.occeans)
    }
}

Solution

  • It would be better to use DispatchGroup for these kinds of situations to execute methods after the completion of multiple completion blocks. Here's an example:

    let dispatchGroup = DispatchGroup()
    
    func fetchContriesAndOceans() {
        fetchCountries()
        fetchOcceans()
        dispatchGroup.notify(queue: .main) {
    //      execute what needs to be executed after the completion of both methods here.
            onCompletion?(self.countries, self.occeans)
        }
    }
    
    func fetchCountries() {
        dispatchGroup.enter()
    //    dispatchGroup.leave() // Put this line in the completion of network call
    }
    
    func fetchOcceans() {
        dispatchGroup.enter()
    //    dispatchGroup.leave() // Put this line in the completion of network call
    }