5

我正在使用此代码循环遍历数组以下载多个文件并写入磁盘。

-(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。

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

4

2 回答 2

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"];
    }
于 2011-12-07T18:55:03.733 回答
5

您可以使用 AFHTTPClient 对BatchOperations进行排队,这有一个完成块,当所有操作完成时会调用它。应该正是您正在寻找的。

于 2013-01-31T16:35:21.377 回答