0

I have an array of video URLs that need to be downloaded. To keep the overall performance, I want to limit the concurrent download counts to 2. For example, I want to start the first two download tasks concurrently at the beginning, then start the third when any of the previous download finishes. At any given time, no more than 2 downloads are executing at the same time. How to achieve this?

It first occurred to me that I should set NSOperationQueue.maxConcurrentOperationCount to 2, then wrapper a NSURLSessionDataTask into a NSOperation and put it in the NSOpeartionQueue. Later I realized that [NSURLSessionDataTask resume] is an asynchronous operation, so all the downloads will start executing almost at the same time.

Another thought is that I put all the tasks in a pending queue first and start the first two downloads. When any task is finished, I check if there are more tasks waiting in the queue and start one if there is.

Is there any better solution?

P. Tsin
  • 435
  • 4
  • 14
  • 1
    Your proposed solution with the max-2 operation queue is fine, actually; you just have to subclass NSOperation so that the networking does not start prematurely and the task does not count as finished until the networking finishes. Very nice explanation here https://fluffy.es/download-files-sequentially/ – matt Mar 26 '20 at 03:35
  • Or if you can be iOS 13 only, Combine framework makes this sort of thing very easy. – matt Mar 26 '20 at 03:36
  • Be sure you do not create the tasks until you are ready to start them. Otherwise, they will time out while waiting. – dgatwood Mar 27 '20 at 21:32

0 Answers0