AFNetworking - 下载多个文件+通过 UIProgressView 进行监控

2024-03-04

我正在尝试将代码从 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];  
}

我认为您必须创建自己的 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);
}];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AFNetworking - 下载多个文件+通过 UIProgressView 进行监控 的相关文章

随机推荐