ios – 如何设置NSURLRequest缓存过期?

前端之家收集整理的这篇文章主要介绍了ios – 如何设置NSURLRequest缓存过期?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用AFNetworking,需要在一个响应中缓存数据几分钟.所以我在应用程序委托中设置NSUrlCache,然后在我的请求中设置它:
NSMutableURLRequest *request = //obtain request; 
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

如何设置到期日期:如果数据在超过n分钟前加载,请从服务器询问响应,而不是从磁盘?

UPD:
假设服务器不支持缓存,我需要在代码中进行管理.

解决方法

所以,我找到了解决方案.

想法是使用连接:willCacheResponse:方法.在缓存响应之前,它将被执行,在那里我们可以改变响应并返回新的,或返回nil,并且响应将不被缓存.当我使用AFNetworking,有一个很好的操作方法

- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection,NSCachedURLResponse *cachedResponse))block;

添加代码

[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection,NSCachedURLResponse *cachedResponse) {
    if([connection currentRequest].cachePolicy == NSURLRequestUseProtocolCachePolicy) {
      cachedResponse = [cachedResponse responseWithExpirationDuration:60];
    }
    return cachedResponse;
  }];

其中responseWithExpirationDuration类别:

@interface NSCachedURLResponse (Expiration)
-(NSCachedURLResponse*)responseWithExpirationDuration:(int)duration;
@end

@implementation NSCachedURLResponse (Expiration)

-(NSCachedURLResponse*)responseWithExpirationDuration:(int)duration {
  NSCachedURLResponse* cachedResponse = self;
  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)[cachedResponse response];
  NSDictionary *headers = [httpResponse allHeaderFields];
  NSMutableDictionary* newHeaders = [headers mutableCopy];

  newHeaders[@"Cache-Control"] = [NSString stringWithFormat:@"max-age=%i",duration];
  [newHeaders removeObjectForKey:@"Expires"];
  [newHeaders removeObjectForKey:@"s-maxage"];

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

  cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:newResponse
                                                            data:[cachedResponse.data mutableCopy]
                                                        userInfo:newHeaders
                                                   storagePolicy:cachedResponse.storagePolicy];
  return cachedResponse;
}

@end

所以,我们根据http/1.1在http header中设置以秒为单位的到期时间为此,我们需要设置一个标题:缓存控制:s-maxage或max-age然后创建新的缓存响应,因为属性是只读的,并返回新的对象.

原文链接:https://www.f2er.com/iOS/329376.html

猜你在找的iOS相关文章