无法获取下载文件的总长度 [英] Can't get the total length of downloading file

查看:169
本文介绍了无法获取下载文件的总长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
}

我在 didReceiveResponse 方法,但下载文件的数据是完美的......请告诉我怎样才能获得下载文件的总长度..

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..

推荐答案

预期的内容长度由您的服务器提供,因此您的iOS应用程序无法控制是否提供。如果无法确定长度,您必须优雅地处理 NSURLResponseUnknownLength 的值,即-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.

正如文档说:


某些协议实现报告内容长度作为响应的一部分,但并非所有协议都能保证提供大量数据。客户应该准备好处理更多或更少的数据。

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.






正如Desdenova指出的那样,这个问题的答案指出 expectedContentLength 可以是 NSURLResponseUnknownLength 如果响应的 Content-Encoding gzip 。你可以通过清除请求的 Accept-Encoding 来禁用 gzip


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"];

注意,如果你这样做,你的回答会更大(例如小JPG的例子)我从我的服务器下载,gzipped有效负载是15k,未压缩的有效负载是25k)。对于小的响应,这种差异可能是不可观察的(但是,如果它那么小,你真的不需要进度更新),但是对于大的响应,它可能变得很重要。

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.

这篇关于无法获取下载文件的总长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆