首页 > 解决方案 > 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有什么变化吗?或者任何其他方式?

标签: iosobjective-ciphonensurlsession

解决方案


-1is NSURLSessionTransferSizeUnknown,这意味着http服务器没有提供“Content-Length”标头(并且数据是使用“Transfer-Encoding: chunked”发送的)。

您可能无能为力。如果https://stackoverflow.com/a/12599242/1187415的解决方法也适用于您的情况,您可以尝试:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:anURL];
[request addValue:@"" forHTTPHeaderField:@"Accept-Encoding"];

推荐阅读