Need to make two HTTP network requests simultaneously (with a completion handler once both finish)

后端 未结 2 1744
轻奢々
轻奢々 2020-12-28 10:22

I have a situation where I need to make two HTTP GET requests and handle their results only after both are finished. I have a completion handler on each individual network r

相关标签:
2条回答
  • 2020-12-28 10:52

    Source: How do I write dispatch_after GCD in Swift 3? You can use dispatch_group for that. For example (ObjC code):

    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
    });
    
    0 讨论(0)
  • 2020-12-28 11:01

    You should use dispatch groups, entering the group before you issue the request, and leaving the group in the completion handler for the request. So, let's assume, for a second, that you had some method that performed an asynchronous request, but supplied a completion handler parameter that was a closure that will be called when the network request is done:

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

    To start these two concurrent requests, and be notified when they're done, you'd 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")
    }
    

    Clearly, your implementation of perform(request:) may vary significantly (e.g. you might have the closure pass the data back), but the pattern is the same whether you are writing your own networking code with URLSession or using Alamofire. Just use GCD groups, entering the group when you create the requests, and leaving the group in the completion handler of the asynchronous request.

    0 讨论(0)
提交回复
热议问题