我正在使用NSOperationQueue和AFNetworking來爲我的項目實現多重下載功能。我也使用核心數據來堅持下載的信息,但我對這部分還是沒問題。我的問題是當涉及到實際創建下載任務。所以這裏是我如何做到這一點:iOS使用NSOperationQueue和AFNetworking實現多重下載功能
// create a NSOperationQueue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.name = @"DownloadQueue";
queue.maxConcurrentOperationCount = 1;
// create an operation (AFDownloadRequestOperation is a subclass of AFHTTPRequestOperation)
AFDownloadRequestOperation *operation = // some initializations
// add the operation to the queue
[queue addOperation:operation];
// later some more operations are created and added to the queue
然後說我向隊列中添加了3個操作。由於我設置maxConcurrentOperationCount
爲1,所以只有1個操作隊列中的運行時,其他2正在等待:
operation 1: running
operation 2: waiting
operation 3: waiting
然後我使用pause
(這是AFURLConnectionOperation
的方法)來暫停正在運行的操作,我希望看到開始運行2個等待操作之一,但它不會發生,2個等待行動仍然等待:
operation 1: paused
operation 2: waiting
operation 3: waiting
我還是要繼續工作1,等到它完成,然後操作2或3將開始運行。
我的問題是如何讓我的隊列中的其他操作運行後,我暫停像我上面解釋的運行操作?
另外,我會非常感激,如果你能解釋一下實現多下載一個更好的方法(特別是涉及到管理下載任務,暫停/恢復下載任務的最大數量)