如何在成功后进行多次网络调用并一起发送结果?

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

我想进行两次网络调用,并且希望仅在两次调用都成功完成后才将结果发送回 viewcontroller。在下面的代码中,我使用了布尔值 gotCountries & gotOcceans 来了解我是否得到响应。我想删除这些布尔标志并确保我使用完成块发送这两个结果。

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)
    }
}

这种情况最好使用DispatchGroup在多个完成块完成后执行方法。这是一个例子:

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
}