本文介绍了AFNetworking - 通过UIProgressView下载多个文件+监控的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to change my code from ASIHTTPRequest to AFNetworking. Currently I want to select 10-15 different HTTP URLs (files) and download them to a documents folder.

使用ASIHTTPRequest非常简单

With ASIHTTPRequest that was pretty easy with

[myQueue setDownloadProgressDelegate:myUIProgressView];

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

In AFNetworking I can't figure out how to do it. I have the following code which downloads the files, stores them and notifies when a file downloads successfully, but I can't create the progress bar for this queue with total size.

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。

I think you will have to create your own UIProgressView, which I will call progressView for the example.

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

这篇关于AFNetworking - 通过UIProgressView下载多个文件+监控的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 09:36