如何通过NSURLConnection了解下载了多少文件

时间:2013-05-08 11:41:28

标签: objective-c nsurlconnection nstimer uiprogressview

我有一个应用程序使用NSURLConnection从url下载文件。 我想什么时候点击下载按钮progressView启动。在progressView的顶部是UILable,显示状态下载。 我想在UILable中显示(“0000 MB下载/ 1000 MB”)。第一部分是文件下载量,第二部分是文件大小。 我不知道如何展示它。 请指导我,并告诉我如何使用progressView的show(下载量/大小文件)。

感谢。

2 个答案:

答案 0 :(得分:4)

使用NSURLConnection's委托方法:

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  [responseData appendData:data];
  NSNumber* curLength = [NSNumber numberWithLong:[responseData length] ];
  NSNumber*filesize = [NSNumber numberWithLong: [response expectedContentLength]
  float progress = [curLength floatValue] / [filesize floatValue] ;
  NSLog(@"progress : %f",progress);
}

答案 1 :(得分:0)

如果使用AFNetworking

此处进度是用于显示下载进度的UIProgressbar

 progress.progress = 0.0;

    currentURL=@"http://www.selab.isti.cnr.it/ws-mate/example.pdf";


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]];
    AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MY_FILENAME_WITH_EXTENTION.pdf"];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

    [operation setDownloadProgressBlock:^(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead) {
        progress.progress = (float)totalBytesRead / totalBytesExpectedToRead;

    }];

    [operation setCompletionBlock:^{
        NSLog(@"downloadComplete!");

    }];
    [operation start];