So, I found the solution.
The idea is to use connection:willCacheResponse:
method. Before cache the response it will be executed and there we can change response and return new, or return nil and the response will not be cached. As I use AFNetworking, there is a nice method in operation:
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
Add code:
[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
if([connection currentRequest].cachePolicy == NSURLRequestUseProtocolCachePolicy) {
cachedResponse = [cachedResponse responseWithExpirationDuration:60];
}
return cachedResponse;
}];
Where responseWithExpirationDuration
from category:
@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
So, we set expiration in seconds in http header according to http/1.1
For that we need one of headers to be set up:
Expires, Cache-Control: s-maxage or max-age
Then create new cache response, because the properties is read only, and return new object.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…