2011-12-07 45 views
5

我正在使用此代码循环访问一个数组以下载多个文件并写入磁盘。AF网络下载多个文件

-(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]; 

,但问题是它调用成功块中的每个文件完成后,(这是它应该),但我只需要一个最终的回调重新加载一些数据,并最终进度HUD。

任何指向正确方向的指针都会很棒。

+0

嘿, 你在哪里调用这个函数?在AppDelegate中还是在特定的控制器中? 另外,如果在下载完成之前退出应用程序会发生什么? 谢谢 – manishKungwani

回答

5

也许有一天这将帮助某人,但我能够使用一种解决方法,可能有重大问题,但它对我的简单用法可以。

我刚从同步数组中删除每行后处理然后运行我需要的代码。

[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"]; 
    } 
5

您可以使用AFHTTPClient来enqueueBatchOperations,这有一个当所有操作完成被称为completionBlock。应该是你正在寻找的。

+0

我同意,这是一个更好的解决方案。 – ajmccall

+1

链接页面现在不可用...... –