问题 AFNetworking - 通过UIProgressView下载多个文件+监控


我正在尝试将我的代码从ASIHTTPRequest更改为AFNetworking。目前我想选择10-15个不同的HTTP URL(文件)并将它们下载到文档文件夹。

使用ASIHTTPRequest非常简单

[myQueue setDownloadProgressDelegate:myUIProgressView];

在AFNetworking中,我无法弄清楚如何做到这一点。我有以下代码下载文件,存储它们并在文件成功下载时通知,但我无法为此队列创建总大小的进度条。

for (i=0; i<3; i++) {

    NSString *urlpath = [NSString stringWithFormat:@"http://www.domain.com/file.zip"];
    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:[NSString stringWithFormat:@"testFile%i.zip",i]];
    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 setDownloadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
        NSLog(@"Sent %d of %d bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path);
    }];

    [myQueue addOperation:operation];  
}

11623
2018-01-29 18:56


起源

嗨,约翰,如果您接受我的答案,如果它适合您,或者如果没有为您解答,我将不胜感激,请告诉我们问题是什么? - Jeshua Lacock
我认为这是因为你提示如何只为一次下载设置进度HUD,而John想要的是整个队列的进度条。 - Michiel van Baak


答案:


我想你必须创建自己的UIProgressView,我将在这个例子中调用progressView。

progressVu = [[UIProgressView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[progressVu setProgressViewStyle: UIProgressViewStyleDefault];

然后只需更新进度条:

[operation setDownloadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {

    float percentDone = ((float)((int)totalBytesWritten) / (float)((int)totalBytesExpectedToWrite));

    progressView.progress = percentDone;

    NSLog(@"Sent %d of %d bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path);
}];

12
2018-01-30 02:53





[operation setDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    float percentDone = ((float)((int)totalBytesRead) / (float)((int)totalBytesExpectedToRead));

    progressView.progress = percentDone;

}];

1
2017-07-08 12:18



此代码显示错误 Incompatible block pointer types sending 'void (^)(NSInteger, long long, long long)' to parameter of type 'void (^)(NSUInteger, long long, long long)' - Dilip
AfNetworking改变了很多,检查最新的操作块。 - Muzammil


想象一下,假设每个文件大小为1 MB,可以通过这种方式下载200多个文件。 当您创建这么多请求(默认超时为30秒)时会发生什么? 30秒后,您将被超时错误轰炸。

只是在说' 马丁


0
2017-10-29 10:29