我在下载文件时尝试查看进度条。该文件是通过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];
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];
}
我尝试了许多不同的事情,不幸的是它没有工作并且保持返回-1。
答案 0 :(得分:9)
如果您的服务器正在使用压缩(它可以透明地执行),则会发生这种情况。您可以通过更改请求Accept-Encoding
参数:
[request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];