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

Negative value in Progress Block during file download

我想下载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

请解决我的问题...

如您的日志所示,totalBytesExpectedToRead 为 -1。当响应 headers.

中未提供 Content-Length 时会发生这种情况

您可以通过让 server-side 人员 return 适当的 Content-Length 来解决这个问题,或者在 iOS 应用程序中显示一个简单的 Activity 指示器而不是进度视图。

您的问题是在服务器中上传 pdf 文件的内容长度 如果未提供 Content-Length HTTP header

,.totalBytesExpectedToRead 为 -1

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