Checking for multiple asynchronous responses from Alamofire and Swift

后端 未结 1 1216
无人及你
无人及你 2020-11-28 08:20

I am writing an application that depends on data from various sites/service, and involves performing calculations based on data from these different sources to produce an en

相关标签:
1条回答
  • 2020-11-28 09:07

    Better than that looping process, which would block the thread, you could use dispatch group to keep track of when the requests were done. So "enter" the group before issuing each of the requests, "leave" the group when the request is done, and set up a "notify" block/closure that will be called when all of the group's tasks are done.

    For example, in Swift 3:

    let group = DispatchGroup()
    
    group.enter()
    retrieveDataFromURL(url1, parameters: firstParameters) {
        group.leave()
    }
    
    group.enter()
    retrieveDataFromURL(url2, parameters: secondParameters) {
        group.leave()
    }
    
    group.notify(queue: .main) {
        print("both requests done")
    }
    

    Or, in Swift 2:

    let group = dispatch_group_create()
    
    dispatch_group_enter(group)
    retrieveDataFromURL(url1, parameters: firstParameters) {
        dispatch_group_leave(group)
    }
    
    dispatch_group_enter(group)
    retrieveDataFromURL(url2, parameters: secondParameters) {
        dispatch_group_leave(group)
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue()) {
        print("both requests done")
    }
    

    The other approach is to wrap these requests within an asynchronous NSOperation subclass (making them cancelable, giving you control over constraining the degree of concurrency, etc.), but that's more complicated, so you might want to start with dispatch groups as shown above.

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