gpt4 book ai didi

ios - AFNetworking 2.0 - 强制缓存

转载 作者:可可西里 更新时间:2023-11-01 03:31:13 24 4
gpt4 key购买 nike

如果不包含ExpiresCache-Control: max-age,是否可以强制响应缓存?

我遇到了 this文章,但不幸的是 URLSession:dataTask:willCacheResponse:completionHandler: 从未在我的 AFHTTPSessionManager 子类中被调用。

感谢任何帮助。

最佳答案

您可以通过实现您自己的不遵循标准 HTTP 缓存规则的 NSURLProtocol 来强制缓存。 complete tutorial is here ,它使用 Core Data 持久化数据,但基本步骤是:

  • 子类 NSURLProtocol
  • +registerClass:注册你的子类
  • 在你的+canInitWithRequest:方法中返回YES,如果这是你第一次看到request,或者NO 如果不是

您现在有两个选择:

  1. 实现您自己的缓存存储(在这种情况下,请按照上面链接的教程进行操作)
  2. 注入(inject)您希望 URL 加载系统遵循的缓存控制 header

假设您想要 #2,在您的协议(protocol)子类中覆盖 connection:didReceiveResponse: 以创建具有您要模拟的缓存控制 header 的响应:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
// Create a dictionary with the headers you want
NSMutableDictionary *newHeaders = [response.allHeaderFields mutableCopy];
newHeaders[@"Cache-Control"] = @"no-transform,public,max-age=300,s-maxage=900";

// Create a new response
NSHTTPURLResponse *newResponse = [[NSHTTPURLResponse alloc] initWithURL:response.URL
statusCode:response.statusCode
HTTPVersion:@"HTTP/1.1"
headerFields:newHeaders];


[self.client URLProtocol:self
didReceiveResponse:newResponse
cacheStoragePolicy:NSURLCacheStorageAllowed];
}

这将导致响应被缓存,就好像服务器已经提供了这些 header 一样。


仅对于 URL session ,您需要设置 session 配置的 protocolClasses。由于您使用的是 AFNetworking,因此看起来像:

[AFHTTPSessionManager sharedManager].session.configuration.protocolClasses = @[[MyURLProtocol class]]

有一些注意事项,因此请确保您 read the protocolClasses documentation .


一些注意事项:

  • 如果有任何方法可以通过让您的服务器发送适当的 header 来解决此问题,请改为这样做。
  • 为了简洁起见,我对“HTTP/1.1”进行了硬编码,但从技术上讲,您应该将其从响应中提取出来。
  • AFNetworking 使用标准的 URL 加载系统,与此问题基本无关。

关于ios - AFNetworking 2.0 - 强制缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com