9
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse    *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    if([recievedData length]) [ recievedData setLength:0 ];

    download_size =[response expectedContentLength];
}

I have this code. download_size is NSInteger. expectedContentLenght always return: -1. Maybe someone know why? I tried use long, but effect was the same.

Thanks for help.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
kolek
  • 3,690
  • 3
  • 24
  • 31

2 Answers2

23

The expected content length is only set when the server provides it, such as by a Content-Length response header. A -1 size means the expected content size is unknown.

If you set Accept-Encoding: gzip on your request, the URL loading system will fib and tell you the expected size is -1, no matter what Content-Length the server sends. This is because it decompresses the data before passing it to you, but it can't know the final uncompressed size till all the data has been downloaded, which is well after you receive this callback.

Jeremy W. Sherman
  • 35,901
  • 5
  • 77
  • 111
  • 1
    To expand on this: If you don't say anything about Accept-Encoding, the server may decide to send gzipped data. To prevent this, use `NSMutableURLRequest` and say `[req setValue:@"" forHTTPHeaderField:@"Accept-Encoding"]`. (I learned this from an answer on a [duplicate question](http://stackoverflow.com/questions/11136020/response-expectedcontentlength-return-1). ) – JWWalker May 15 '17 at 20:27
0

As long as I know, NSURLResponse does not update that property. You need to use NSHTTPURLResponse instead...

Ariel
  • 2,430
  • 1
  • 17
  • 20
  • I change declaration to: -(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { Still return -1. Should I modify any other function? – kolek Sep 15 '11 at 06:23
  • As Jeremy pointed, you should check if the server provides you with that data. -1 is the NSURLResponseUnknownLength. (thought I do believe nsurl should give you the value in the case of zipping. The straight vision tells us that the value should cover the transfer size not the uncompressed one. But I can't bite for that as I don't know exact implementation of it) – Ariel Sep 15 '11 at 08:29