NSURLConnection expectedContentLength返回-1

GSK*_*985 4 ios progress-bar

我正在尝试在下载文件时查看进度条.该文件是通过PHP生成的,我发送的是"Content-length"标题,实际上可以正常工作.

文件下载正常,这不是问题.不幸的是,我无法获取文件大小以便正确显示进度条.

这是我的代码:

write_to_filename = [issue objectForKeyedSubscript:filename];
NSString *post =[[NSString alloc] initWithFormat:@"user_id=%@&email=%@&password=%@",[userData stringForKey:@"userId"],[userData stringForKey:@"email"],[userData stringForKey:@"password"]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://MY_API_REQUEST"]];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

[request setValue:@"application/pdf" forHTTPHeaderField:@"Accept"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];

[issueArray writeToFile:[self saveFilePath] atomically:YES];
Run Code Online (Sandbox Code Playgroud)

NSURLConnection

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse 

*)response {

    NSLog(@"%lld",[response expectedContentLength]);
    _responseData = [[NSMutableData alloc] init];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {

    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:write_to_filename];
    [_responseData writeToFile:fileName atomically:YES];

    write_to_filename = nil;
    _responseData = nil;

    [[self IssuesOverviewCollection] reloadData];

}
Run Code Online (Sandbox Code Playgroud)

我尝试了很多不同的东西,遗憾的是它不起作用并保持返回-1.

Rob*_*Rob 9

如果您的服务器采用压缩(它可以透明地执行),就会发生这种情况.您可以通过更改请求Accept-Encoding参数来关闭服务器上的压缩:

[request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
Run Code Online (Sandbox Code Playgroud)