You must make two HTTP network requests at the same time (with a completion handler after both are completed)

I have a situation where I need to make two HTTP GET requests and process their results only after they are completed. I have a completion handler for each individual network request, but this does not help, since I do not know when the data is extracted from both requests.

I have limited experience with GCD, but now that Swift 3 is out, I'm trying to figure out how to complete several tasks and have one completion handler for them. My research has shown that a GCD or NSOperationQueue solution may be the solution I'm looking for. Can anyone help suggest what tool is suitable for working and what the code looks like in Swift 3?

+4
source share
2 answers

You must use the send groups included in the group before issuing the request and leaving the group in the completion handler for the request. So, suppose for a second you had some method that performed an asynchronous request, but provided a completion handler parameter, which was a closure that would be called when the network request was executed:

func perform(request: URLRequest, completionHandler: @escaping () -> Void) { ... }

To run these two simultaneous requests and get notified when they are done, you will do something like:

let group = DispatchGroup()

group.enter()
perform(request: first) {
    group.leave()
}

group.enter()
perform(request: second) {
    group.leave()
}

group.notify(queue: .main) {
    print("both done")
}

, perform(request:) (, ), , , URLSession Alamofire. GCD, .

+13

: dispatch_after GCD Swift 3? dispatch_group . ( ObjC):

dispatch_group_t group = dispatch_group_create();

//startOperation1
dispatch_group_enter(group);

//finishOpeartion1
dispatch_group_leave(group);


//startOperation2
dispatch_group_enter(group);

//finishOpeartion2
dispatch_group_leave(group);


//Handle both operations completion
dispatch_group_notify(group, dispatch_get_main_queue(), ^{ 
//code here
});
-1

Source: https://habr.com/ru/post/1654824/


All Articles