Skip to content

Instantly share code, notes, and snippets.

@delebedev
Created November 1, 2013 14:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delebedev/7266332 to your computer and use it in GitHub Desktop.
Save delebedev/7266332 to your computer and use it in GitHub Desktop.
NSURLCache trick to control cache on client side
typedef NSCachedURLResponse * (^WGNCachedResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
- (WGNCachedResponseBlock)cacheResponseBlockWithTime:(NSTimeInterval)time {
return ^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)[cachedResponse response];
NSDictionary *headers = [httpResponse allHeaderFields];
NSString *cacheControl = [headers valueForKey:@"Cache-Control"];
NSString *expires = [headers valueForKey:@"Expires"];
if((cacheControl == nil) && (expires == nil)) {
NSMutableDictionary *modifiedHeaders = [httpResponse.allHeaderFields mutableCopy];
[modifiedHeaders addEntriesFromDictionary:@{@"Expires": [NSDate RFC822StringFromDate:[[NSDate date] dateByAddingTimeInterval:time]], @"Cache-Control": @"public"}];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:httpResponse.URL
statusCode:httpResponse.statusCode
HTTPVersion:@"HTTP/1.1" headerFields:modifiedHeaders];
NSCachedURLResponse *modifiedCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response
data:cachedResponse.data
userInfo:cachedResponse.userInfo
storagePolicy:NSURLCacheStorageAllowed];
return modifiedCachedResponse;
}
return cachedResponse;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment