why [response expectedContentLength] always return -1
Asked Answered
A

2

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.

Altar answered 14/9, 2011 at 14:2 Comment(0)
W
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.

Wizard answered 15/9, 2011 at 6:30 Comment(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. )Jillion
E
0

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

Evette answered 14/9, 2011 at 14:7 Comment(2)
I change declaration to: -(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { Still return -1. Should I modify any other function?Altar
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)Evette

© 2022 - 2024 — McMap. All rights reserved.