Created
November 1, 2013 14:36
-
-
Save delebedev/7266332 to your computer and use it in GitHub Desktop.
NSURLCache trick to control cache on client side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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