0

I have a swift class that does runs a multi-step process, much like this question has: Simple GCD Serial Queue example like FIFO using blocks

So i have a single public method of func start(), then a bunch of private methods which contain each "step" of the process.

I've spoken to a few people about this and i've been told i don't need to use a load of completion handlers and can instead use a serial dispatch queue.

However, if some of those steps run something that contains its own queue, then the method will end (and the next step starts) before it really has completed. So for example if func step1() uses Alamofire to download some data from an API, and step2() turns the response json into data models, step1() will return before the network response comes in. This is why i originally used callbacks, however i'm being told i don't need them?

The only way i can see a serial queue working is if there was a way of manually telling the queue when a certain task is complete (which there isn't?).

Could anyone help me work out the best way to structure and run this multi-step process, preferably without a load of nested completion handlers?

Or in other words: How do you use serial dispatch queues if some of the tasks you push to the queue will do things like network requests that return immediately.

Community
  • 1
  • 1
TRG
  • 845
  • 1
  • 9
  • 22

1 Answers1

0

You can use NSOperationQueue for that. NSOperationQueue is built on top of GCD and specially designed to manage a number of dependent jobs.

Anton Chikin
  • 1,746
  • 2
  • 17
  • 22
  • I was looking at these, presumably i would use `dispatch_semaphore_create` in order to make it wait for the network request to finish as per this blog post: http://www.oded-tech-blog.com/ios-swift-how-to-wait-for-async-network-call-in-nsoperation/ ... Guessing there's no other way to do this unless i fall back to completion callback nesting – TRG Nov 02 '16 at 20:26
  • You can wrap Almofire into NSOperation http://stackoverflow.com/questions/27021896/nsurlsession-concurrent-requests-with-alamofire – Anton Chikin Nov 02 '16 at 21:32