user748001
user748001

Reputation: 181

How to download multiple files in Queue in iOS

i need to download multiple files in queue. When i try to download single file it works perfectly fine, however when i try to download multiple file it start downloading at the same time with first download, i need to keep them in queue until first download is finished and then work with second download. I am using AFNetworking Library extension AFDownloadRequestOperation. Below is my code. Please help me regarding this, if there is any thing i am doing wrong.

         NSURLRequest *request = [NSURLRequest requestWithURL:videoURL];

         AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
         [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
             if(operation.response.statusCode == 200) {

                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Successfully Downloaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                 [alertView show];
             }

         }failure:^(AFHTTPRequestOperation *operation, NSError *error) {

             if(operation.response.statusCode!= 200) {

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Error While Downloaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                 [alertView show];
             }
         }];

         [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {

             float percentDone = ((float)totalBytesRead) / totalBytesExpectedToReadForFile;
             delegate.progressDone = percentDone;
             [progressTableView reloadData];
         }];
         [operation start];

Upvotes: 2

Views: 2755

Answers (1)

Matthew Abbott
Matthew Abbott

Reputation: 36

Create the requests and add them to an instance of AFHTTPClient's operation queue:

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:nil];

// Important if only downloading one file at a time
[client.operationQueue setMaxConcurrentOperationCount: 1];

NSArray *videoURLs; // An array of strings you want to download

for (NSString * videoURL in videoURLs) {

    // …setup your requests as before

    [client enqueueHTTPRequestOperation:downloadRequest];
}

Your first request will start as soon as it is added to AFHTTPClient's operation queue but subsequent requests will wait in turn for the previous operation to end.

Upvotes: 2

Related Questions