json - AFNetworking + JSON + 进度下载

标签 json afnetworking

我正在使用 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];

我的结果:

Get 27129 of -1 bytes

Get 127481 of -1 bytes

Get 176699 of -1 bytes

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

最佳答案

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

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

关于json - AFNetworking + JSON + 进度下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9201332/

相关文章:

swift - 将 Obj-C block 转换为 Swift 以进行 AFNetworking 调用

从 iOS 应用程序调用脚本时未维护 PHP session 数组

java - 避免在 Java 中使用相同的 try catch block

php - 数据的返回值使用ajax、jquery、json

json - PHP7、JSON 和 Zend(解码失败 : syntax error)

ios - 如何在 Alamofire 中设置 requestSerializer

php - 在 PHP 中运行 C++ 脚本

json - 可靠的 : multy loop into json file

ios - 如何保护来自代理的api调用

ios - AF网络 : Getting "finished with error - code: -999" warning