Task中的totalBytesExpectedToWrite为

Task中的totalBytesExpectedToWrite为

本文介绍了NSURLSessionDownloadTask中的totalBytesExpectedToWrite为-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个奇怪的问题.我使用NSURLSessionNSURLSessionDownloadTask从Internet加载文件.这是代码

I faced with a strange problem. I load file from the Internet using NSURLSession and NSURLSessionDownloadTask. Here is the code

NSURLSessionConfiguration *sessionConfiguration =
[NSURLSessionConfiguration backgroundSessionConfiguration:kSessionId];
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
                                             delegate:self
                                        delegateQueue:[NSOperationQueue new]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request];
[downloadTask resume];

我的课程被声明为NSURLSessionDownloadDelegate,并且我得到了很好的回调.但是当系统调用委托方法

My class is declared as NSURLSessionDownloadDelegate and I get callbacks well. But when the system calls the delegate method

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"totalBytesExpectedToWrite: %lld", totalBytesExpectedToWrite);
    NSLog(@"%lld", totalBytesWritten);
}

totalBytesExpectedToWrite始终等于-1,并且我无法向用户显示进度,因为我不知道下载文件的大小.

totalBytesExpectedToWrite always equal -1 and I have no ability to show a progress to user because I don't know the downloading file's size.

您能提示我哪里出错了吗?

Could you prompt me where I made a mistake?

推荐答案

-1NSURLSessionTransferSizeUnknown,这意味着http服务器未提供"Content-Length"标头(然后使用"Transfer-Encoding:分块"发送数据).

-1 is NSURLSessionTransferSizeUnknown, which means that the http server did not providea "Content-Length" header (and the data is sent using "Transfer-Encoding: chunked").

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

There is probably not much that you can do. You could try if the workaround from https://stackoverflow.com/a/12599242/1187415 works in your case as well:

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

这篇关于NSURLSessionDownloadTask中的totalBytesExpectedToWrite为-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:05