无法在 AFNetworking 中获取下载进度

Posted

技术标签:

【中文标题】无法在 AFNetworking 中获取下载进度【英文标题】:Not able to get the download progress in AFNetworking 【发布时间】:2014-12-17 13:30:11 【问题描述】:

我正在尝试使用以下代码使用 AFNetworking 2.0 下载文件

AFHTTPRequestSerializer *serialize = [AFHTTPRequestSerializer new];
[serialize setAuthorizationHeaderFieldWithUsername...// set the auth header with username and password
serialize.timeoutInterval = 200;
NSError *error = nil;
NSMutableURLRequest *request = [serialize requestWithMethod:@"GET" URLString:url parameters:nil error:&error];
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
NSProgress *progress = nil;

NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) 
    NSLog(@"success….”);
    NSURL *url = [NSURL new];
    return url;
 completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) 
    NSLog(@"error: %@", error.localizedDescription);
    ];

[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
[downloadTask resume];

// 在此处添加观察者以获取进度

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context


dispatch_async(dispatch_get_main_queue(), ^
    if ([keyPath isEqualToString:@"fractionCompleted"]) 
        NSProgress *progress = (NSProgress *)object;
        NSLog(@"Progress… %f total unit count =%lld , completed unit count =%lld", progress.fractionCompleted , progress.totalUnitCount,progress.completedUnitCount);
     else 
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    
);


这是来自 observeValueForKeyPath 方法的 NSLog

SampleDownload[5833:149756] Progress… 0.000000 total unit count =-1 , completed unit count =0
SampleDownload[5833:149756] Progress… 0.000000 total unit count =-1 , completed unit count =975
SampleDownload[5833:149767] Progress… 0.000000 total unit count =-1 , completed unit count =25149
SampleDownload[5833:149767] Progress… 0.000000 total unit count =-1 , completed unit count =31086
SampleDownload[5833:149767] Progress… 0.000000 total unit count =-1 , completed unit count =53006
SampleDownload[5833:149754] Progress… 0.000000 total unit count =-1 , completed unit count =54377
SampleDownload[5833:149755] Progress… 0.000000 total unit count =-1 , completed unit count =66098
SampleDownload[5833:149768] Progress… 0.000000 total unit count =-1 , completed unit count =93626
SampleDownload[5833:149763] Progress… 0.000000 total unit count =-1 , completed unit count =103805

所以你可以看到我得到的总单位数是-1。因此,我认为 fractionCompleted 为 0,我无法更新 UI。我犯了什么错误?

我已将此作为参考。 How to get download progress in AFNetworking 2.0?

在这个线程上也有一些类似的讨论,但我无法弄清楚原因。 https://github.com/AFNetworking/AFNetworking/issues/1398

编辑

发布响应头


"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Headers" = "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With";
"Access-Control-Allow-Methods" = "GET, POST, PUT, DELETE, OPTIONS";
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "public, max-age=43200";
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Length" = 1166764;
"Content-Type" = "application/pdf";
Date = "Wed, 17 Dec 2014 12:17:43 GMT";
Etag = “someEtag”;
Expires = "Thu, 18 Dec 2014 00:17:43 GMT";
"Last-Modified" = "Wed, 17 Dec 2014 11:58:31 GMT";
Server = "nginx/1.4.6 (Ubuntu)";
Vary = "Accept-Encoding";

【问题讨论】:

检查服务器是否返回Content-Length @Andy 谢谢!使用我得到的响应标头更新了问题详细信息。 嗯我不知道,对我来说一切似乎都是合法的.. 见 ***.com/questions/9550971/afnetworking-progress 和 ***.com/questions/7417610/…(请记住,在 Google 中搜索此内容时,如果您在搜索字词中包含 -1,我认为它不包括 所有提到数字 1 的页面,无论是正面的还是负面的!- 是 Google 的 "Remove words" operator。) 【参考方案1】:

问题可能是gzipContent-Encoding,这可能导致NSURLSessionDownloadDelegate 方法didWriteData 为预期的总字节数返回-1。您可以尝试在发出请求之前通过设置Accept-Encoding 来禁用gzip

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

【讨论】:

以上是关于无法在 AFNetworking 中获取下载进度的主要内容,如果未能解决你的问题,请参考以下文章

AFNetworking 3.0 setImageWithURLRequest 下载进度

AFNetworking 2.0 - 在监控进度的同时批量下载图像

使用 AFNetworking 计算下载多个文件的总进度

显示使用 AFNetworking 下载图像的进度

AFNetworking 检查进度

如何使用 AFNetworking 在 UILabel 中设置 UIProgressView 的下载状态?