Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFnetworking downloading multiple files

I'm using this code to loop through an array to download multiple files and write to disk.

-(void)download
{
//set url paths
for (NSString *filename in syncArray)
{
    NSString *urlpath = [NSString stringWithFormat:@"http://foo.bar/photos/%@", filename];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlpath]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:filename];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];


[operation start];

but the problem is it calls the success block after each file is done, (which it should) but I just need one final call back to reload some data and end a progress HUD.

Any pointers in the right direction would be great.

like image 751
BigB Avatar asked Dec 07 '11 00:12

BigB


2 Answers

Maybe someday this will help someone, but I was able to use a workaround that probably has major issues but its okay for my simple usage.

I just deleted each line from the sync array after it was processed then ran my code i needed.

 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
    [SVProgressHUD showWithStatus:@"Updating Photos"];
    [syncArray removeObject:filename];
    if (!syncArray || !syncArray.count) 
    {
    NSLog(@"array empty");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self];
        [SVProgressHUD dismissWithSuccess:@"Photos Updated"];
    }
like image 84
BigB Avatar answered Nov 23 '22 14:11

BigB


You can use AFHTTPClient to enqueueBatchOperations and this has a completionBlock which is called when all operations are finished. Should be exactly what you're looking for.

like image 20
Alfie Hanssen Avatar answered Nov 23 '22 13:11

Alfie Hanssen