简体   繁体   English

AFnetworking下载多个文件

[英]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. 但问题是它在每个文件完成后调用成功块(它应该),但我只需要最后一次回调来重新加载一些数据并结束进度HUD。

Any pointers in the right direction would be great. 任何正确方向的指针都会很棒。

You can use AFHTTPClient to enqueueBatchOperations and this has a completionBlock which is called when all operations are finished. 您可以使用AFHTTPClient进行enqueueBatchOperations ,这有一个completionBlock,在所有操作完成后调用。 Should be exactly what you're looking for. 应该是你正在寻找的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM