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