【问题标题】:Why am I getting 'Content-Length' with AFNetworking but not with Alamofire?为什么我使用 AFNetworking 获得“内容长度”,而使用 Alamofire 却没有?
【发布时间】:2018-10-02 23:53:56
【问题描述】:

在 Swift (Alamofire) 中,我执行以下代码:

let url = URL(string: "http://cdn.thechivemobile.com.edgesuite.net/v5/chive/20117177/20117177_2_600_366.gif")!
let task = Alamofire.request(url)
task.downloadProgress() { (progress) in
    print("*** \(progress.completedUnitCount) \(progress.totalUnitCount)\n")
}

progress.totalUnitCount 总是-1。

但是有了这个 Objective-C (AFNetworking) 代码:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://cdn.thechivemobile.com.edgesuite.net/v5/chive/20117177/20117177_2_600_366.gif"]];
AFHTTPRequestOperation *httpOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    NSLog(@"*** %@", @(((double)totalBytesRead) / ((double)totalBytesExpectedToRead)));
}];
[httpOperation start];

totalBytesExpectedToRead 有效。 我查看了标题,它们略有不同。 Objective-C 代码获取带有Content-Length 的标头,Swift 代码没有。

【问题讨论】:

  • 你确定响应没有被缓存吗?服务器正在使用 ETag 缓存。如果响应被缓存,您将无法获得进度,因为图像实际上并未下载,而是从缓存中加载。
  • @Sulthan 我读它的方式是对象是压缩存储的。请看下面我的回答。我仍然不确定为什么 Alamofire 的做法与 AFNetworking 不同。

标签: ios swift alamofire afnetworking-3


【解决方案1】:

问题是我需要为 Alamofire 添加“Accept-Encoding: gzip”。我不需要使用 AFNetworking 执行此操作。

request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")

似乎 Akamai 可能会将这些图像缓存为压缩对象并在下载它们之前解压缩它们。当它这样做时,它不会提前知道解压缩的内容大小,因此它不包括“Content-Length”。

【讨论】:

  • 我将它添加到标题中但仍然无法正常工作,totalUnitCount 总是 = -1,然后我下载的文件比服务器大小大,你遇到过这个问题吗?
  • @famfamfam 我最终的解决方案是停止使用 Alamofire。我确实遇到过类似的问题,如果我没记错的话,我们在服务器上解决了这个问题
  • 谢谢,我改为获取下载链接,而不是查看器链接(如文档),现在可以使用了
猜你喜欢
  • 1970-01-01
  • 2016-08-02
  • 2010-10-15
  • 2019-06-04
  • 1970-01-01
  • 2016-04-23
  • 2020-06-17
  • 2011-03-17
  • 2018-10-15
相关资源
最近更新 更多