gpt4 book ai didi

ios - 无法获取下载文件的总长度

转载 作者:行者123 更新时间:2023-11-28 20:05:05 24 4
gpt4 key购买 nike

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 方法中得到长度 -1 但下载文件的数据是完美的...请告诉我如何获得要下载的文件的总长度..

最佳答案

预期的内容长度由您的服务器提供,因此您的 iOS 应用无法控制它是否提供。如果无法确定长度,则必须优雅地处理 NSURLResponseUnknownLength 的值,即 -1。

作为the documentation说:

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 指出的那样,this question 的答案指出如果响应的 Content-Encodinggzip,则 expectedContentLength 可以是 NSURLResponseUnknownLength。您可以通过清除请求的 Accept-Encoding 来禁用 gzip:

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

请注意,如果您这样做,您的响应会更大(例如,在我从服务器下载的小型 JPG 示例中,gzipped 有效负载为 15k,未 gzip 有效负载为 25k)。对于小的响应,这种差异可能无法观察到(但是,再说一遍,如果它很小,您真的不需要进度更新),但对于大的响应,它可能会变得很重要。

关于ios - 无法获取下载文件的总长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22352116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com