使用代理
- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response {
下载大小可以通过以下方式获取:
downloadSize = [response expectedContentLength];
但我的downloadSize有时是-1。有时它是正确的值,但有一半时间返回-1。
stackoverflow上的这个答案显示了一个可能的解决方案,并解释了为什么我得到值-1:why [response expectedContentLength] always return -1。
我试过了:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:_downloadURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setValue:@"" forHTTPHeaderField:@"Accept-Encoding"]; //Don't use Gzip to see total size of download
但这并没有改变一件事。有谁知道为什么expectedContentLength给我值-1?再次它只给我一半的时间我尝试。有时它是oke。
修改 当我使用代码
时,我在DidReceiveResponse中记录了[response AllHeaderFiles][request setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
"Content-Type" = "text/html";
Date = "Mon, 16 Sep 2013 12:43:54 GMT";
Server = "Apache/2";
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.2.17";
这是没有该代码的输出:
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Length" = 1500;
"Content-Type" = "text/html";
Date = "Mon, 16 Sep 2013 12:38:56 GMT";
Server = "Apache/2";
Vary = "Accept-Encoding,User-Agent";
"X-Powered-By" = "PHP/5.2.17";
但是无论我得到-1还是下载大小,两个输出都保持不变。