Search code examples
iosnsurlsessiondownloadtask

Several DownloadTasks sequentially


I have n tasks sending to a server. When I launch them by [taskN resume] they will launch parallelly but i want to launch them sequentially - if first task finish, other task will launch. Any suggestions?


Solution

  • For this you are best using NSOperation and NSOperationQueue.

    It manages a queue of tasks and each one is performed on a background thread.

    By setting the queue to only have 1 concurrent operation it will queue them up like you want.

    You should...

    1. Create an NSOperation subclass that does your downloading. Make it do SYNCHRONOUS downloads. They don't need to be asynchronous as they will already be on a background thread.

    2. Set up an NSOperationQueue and set maximumNumberOfConcurrentOperations to 1.

    3. Add your operations to the queue.

    This is the easiest way to approach NSOperationQueue but there are many more things that you can do with it.

    There are also several questions and tutorials about it so I won't go into full detail here as you should be able to find other SO questions.