文件下载期间进度块中的负值

时间:2016-04-06 08:23:02

标签: ios afnetworking uiprogressview

我想下载pdf文件。当我下载小的pdf文件然后我得到加值但是当我下载大文件然后我使用afnetworking得到负值。

这是我的代码:

- (IBAction)download:(id)sender {


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    NSString *pdfName = @"The_PDF_Name_I_Want.pdf";

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pdfName];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

        NSLog(@"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);
                self.progressView3.progress = (float)totalBytesRead / totalBytesExpectedToRead;

    }];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

    [operation start];
}

查看我的输出

2016-04-06 15:04:53.842 pdf[8149:60b] Download = -811521.000000
2016-04-06 15:04:53.849 pdf[8149:60b] Download = -817179.000000
2016-04-06 15:04:53.860 pdf[8149:60b] Download = -819123.000000
2016-04-06 15:04:53.872 pdf[8149:60b] Download = -823469.000000
2016-04-06 15:04:53.879 pdf[8149:60b] Download = -826393.000000
2016-04-06 15:04:53.921 pdf[8149:60b] Download = -827820.000000
2016-04-06 15:04:53.932 pdf[8149:60b] Download = -830744.000000
2016-04-06 15:04:53.939 pdf[8149:60b] Download = -833662.000000

请解决我的问题...

2 个答案:

答案 0 :(得分:1)

正如您的日志所示,totalBytesExpectedToRead为-1。如果响应标头中未提供Content-Length,则会发生这种情况。

您可以通过要求服务器端人员返回相应的Content-Length来处理此问题,或者通过显示简单的活动指示器而不是进度视图来在iOS应用程序中处理此问题。

答案 1 :(得分:1)

您的问题是在服务器上传pdf文件的内容长度     如果未提供Content-Length HTTP标头,则.totalBytesExpectedToRead为-1

由server.you应该将此标头添加到您的服务器,或通过显示UIActivityIndi​​cator而不是UIProgressView来处理-1。