1

Using Alamofire I need to make a set of server requests and wait until all of them either succeed or fail and collect the results into a result object.

Is there a proper/provided way to do this in Alamofire?

I could put the each individual result into a queue and wait until the count is = total # of requests (obviously in a separate thread) but that seems a little clunky.

ahwulf
  • 2,584
  • 15
  • 29
  • This question and answer address how to do it in Objective-C, the translation is pretty straight-forward: http://stackoverflow.com/questions/23253175/how-to-tell-if-blocks-in-loop-all-have-completed-executing/23253323#23253323 – David Berry Nov 25 '15 at 16:55
  • Or http://stackoverflow.com/a/28101212/1271826 – Rob Nov 25 '15 at 17:40

1 Answers1

2

To summarize this question and answer How to tell if blocks in loop all have completed executing?, you want to create a dispatch group, enter the group as you start each operation, exit the group as you complete each operation, and finally use display_group_notify to execute a block once the group has completed:

let group = dispatch_group_create()

foreach operation {
    dispatch_group_enter(group)

    startOperation(..., completion:{
        dispatch_group_leave(group)
    })
}

dispatch_group_notify(group, dispatch_get_main_queue()) {
    // code to run when all operations complete
}
Community
  • 1
  • 1
David Berry
  • 40,941
  • 12
  • 84
  • 95
  • I'm doing this but dispatch_group_leave() crashes the first time it is called. This code is in a function in a class instance which is stored in a static var (test code not a real app) so the instance doesn't dealloc. The "operations" are Alamofire requests and the completion returns the result. The completion is apparently run in the main thread which I'm guessing causes the crash or could there be another issue? The group is an instance var. – ahwulf Nov 25 '15 at 18:16
  • No clues without some actual code and an indication of what the error is. – David Berry Nov 25 '15 at 18:20
  • Ah never mind, stupid error. The answer works correctly. I failed to balance the enter and leave correctly. – ahwulf Nov 25 '15 at 18:21
  • There ya go :) Also remember that if there are separate error and success callbacks you'll need to put a leave in both. – David Berry Nov 25 '15 at 18:22