2

我正在使用 AFNetworking 并且非常喜欢它。我需要从我的服务器获取 JSON 数据,这没关系,它运行良好。

我添加了 setDownloadProgressBlock 但我认为它不能与 JSON 下载一起使用:也许无法获得估计的要下载的字节数。

我的代码:

  NSMutableURLRequest *request = [[VinocelaHTTPClient sharedClient] requestWithMethod:@"GET" path:@"ws/webapp/services/pull" parameters:nil];
  
  AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
                                                                                      success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
  {
  }  
     
  } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
  {
  }];
                                       
  [operation setDownloadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSLog(@"Get %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);

  }];
  
  [operation start];

我的结果:

获取 27129 个 -1 个字节

获取 127481 个 -1 个字节

获取 176699 个 -1 个字节

所以,我认为 AFNetworking 在下载与 zip 文件或图像相反的 JSON 数据时无法估计要下载的实际大小?

4

1 回答 1

2

从阅读源代码来看,进度回调似乎只是传递了expectedContentLength缓存的内部NSHTTPURLResponse对象的属性。因此,如果由于某种原因您的服务器未正确发送Content-Length标头,和/或正在执行分块传输编码,则该值是未知的,并且该值NSURLResponseUnknownLength被返回(恰好被定义为 -1)。

尝试检查应用程序上下文之外的 HTTP 请求返回的标头。如果您得到一个Content-Length值正常的标头,则问题可能出在 AFNetworking 本身。如果不存在,则问题出在服务器上。我从未见过 HTTP 服务器使用分块传输编码发送 JSON 响应(大多数情况下,内容大小应该相对较小,并且在发送标头时已知),但这样做符合规范。

于 2012-02-08T21:17:09.073 回答