salmancs43 salmancs43 - 5 months ago 41
Objective-C Question

Download one file at a time using afnetworking

I have an

array
which contains different URLs. I want to download one file with a progress bar, than start the next one and so on.

Here is my code that I have so far;

-(void) func:(NSArray *) arry
{

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 900;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSMutableArray * downloadedUrl = [[NSMutableArray alloc] init];
for (NSString * str in arry) {
NSURL *URL = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL (NSURL targetPath, NSURLResponse response) {
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];

return [tmpDirURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse response, NSURL filePath, NSError *error) {

if(error)
{
NSLog(@"File Not Dowloaded %@",error);

}

}];
[downloadTask resume];
}
}


How would you download one file at a time with a progress bar and then remove the url from array?

Answer

Declare one global NSMutableArray of file and used that in the function like below.

-(void) downloadFile {

     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
     configuration.timeoutIntervalForRequest = 900;
     AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

     NSURL *URL = [NSURL URLWithString:[self.fileArr firstObject]]; //Here self.fileArr is your global mutable array
     NSURLRequest *request = [NSURLRequest requestWithURL:URL];

     NSURLSessionDownloadTask downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL (NSURL targetPath, NSURLResponse response) {
     NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];

        return [tmpDirURL URLByAppendingPathComponent:[response suggestedFilename]];
     } completionHandler:^(NSURLResponse response, NSURL filePath, NSError *error) {

        if(error)
        {
            NSLog(@"File Not Dowloaded %@",error);
            [self downloadFile];
        }
        else {
            [self.fileArr removeObjectAtIndex:0];
            if (self.fileArr.count > 0) {
                [self downloadFile];
            }
        }
    }];
    [downloadTask resume];
}

Now call this function but before that initialize self.fileArr and after that call downloadFile method.

Hope this will help you.