问题
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..
回答1:
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.
来源:https://stackoverflow.com/questions/22352116/cant-get-the-total-length-of-downloading-file