0
NSMutableURLRequest *objRequest =[[NSMutableURLRequest alloc]initWithURL:url1];

[objRequest setHTTPMethod:@"POST"];
[objRequest setHTTPBody:[NSData dataWithBytes:(__bridge const void *)(dict) length:[dict count]]];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:url1] 
                                                             delegate:self];
[connection start];


-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    length = [response expectedContentLength];
    NSLog(@"%f",length);
}

i get length -1 in didReceiveResponse method but the data of downloaded file is perfect ...pls tell me how can i get total length of file to be downloded..

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Sarthak Patel
  • 129
  • 2
  • 8
  • 2
    Unrelated, but don't call `[connection start]`. The `initWithRequest:delegate:` already starts your connection. – Rob Mar 12 '14 at 12:54
  • Try to find data length in `didReceiveData:` – Himanshu Joshi Mar 12 '14 at 12:58
  • 1
    Try this, looks promising http://stackoverflow.com/questions/11136020/response-expectedcontentlength-return-1 – Desdenova Mar 12 '14 at 12:59
  • 1
    @Desdenova Good catch. I notice that this allows me to use `expectedContentLength` in my request, where I historically was getting `-1`, but I also noticed (watching the request and response in [Charles](http://charlesproxy.com)) that when my response was not `gzip`, I lost the compression and unsurprisingly the response was much larger. For large downloads, this could probably have a material impact on performance/bandwidth. – Rob Mar 12 '14 at 19:06

1 Answers1

3

The expected content length is provided by your server, so your iOS app doesn't have control of whether it's provided or not. You must gracefully handle a value of NSURLResponseUnknownLength, i.e. -1, if the length can’t be determined.

As the documentation says:

Some protocol implementations report the content length as part of the response, but not all protocols guarantee to deliver that amount of data. Clients should be prepared to deal with more or less data.


As Desdenova points out, the answer to this question points out that expectedContentLength can be NSURLResponseUnknownLength if the Content-Encoding of the response is gzip. You can disable gzip, by clearing the request's Accept-Encoding:

[request setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];

Note, if you do this, your response will be larger (e.g. in an example of a small JPG I'm downloading from my server, the gzipped payload was 15k, the un-gzipped payload was 25k). This difference may not be observable for small responses (but then, again, if it was that small, you don't really need progress updates), but for large responses, it may become material.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044