ios - URLSession 委托函数 totalBytesExpectedToWrite 总是返回 -1
问题描述
我已经创建了用于下载文件的 URLSession,文件正在正确下载,这没有问题。
我想显示剩余字节的百分比,但是委托函数:
-(void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
并且它的参数totalBytesExpectedToWrite
总是返回-1。
几天前一切正常,代码没有变化,但它突然停止发送预期字节。
我的请求代码如下:
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:fileUrl];
NSDictionary*param = [[NSDictionary alloc]initWithObjectsAndKeys:@"",@"Accept-Encoding", nil];
[request setAllHTTPHeaderFields:param];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];
[downloadTask resume];
我缺少的api有什么变化吗?或者任何其他方式?
解决方案
-1
is NSURLSessionTransferSizeUnknown
,这意味着http服务器没有提供“Content-Length”标头(并且数据是使用“Transfer-Encoding: chunked”发送的)。
您可能无能为力。如果https://stackoverflow.com/a/12599242/1187415的解决方法也适用于您的情况,您可以尝试:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:anURL];
[request addValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
推荐阅读
- actions-on-google - 可以从操作控制台导入/导出 Google 操作吗?
- reactjs - 如果使用 useEffect 更改了另一个过滤器,则重置为第一页
- python - 试图发送一个 Scrapy 爬虫来爬取从其第一个目的地拉出的一批链接(递归爬取)。怎么做?
- css - 在头像图像设置高度=自动不起作用
- html - 如果使用 iTextsharp 第一页的某些内容和第二页的某些内容,想要将整个表格 tr 移动到下一页
- perl - 关于 perl 引用优先级的困惑
- python - 为 PyQtWebEngine 的隐身模式添加选项卡
- asp.net-mvc - 在 Linq 中使用 GroupBy 时如何通过用户 ID 获取内容
- javascript - 从给定的数字返回最大可能的数字?javascript
- c++ - int[8][8] 类型的参数变成 int(*)[8]