Last active
November 7, 2020 01:41
-
-
Save pgor/6252124 to your computer and use it in GitHub Desktop.
NSURL mechanism doesn't automatically set last-modified or etag headers, so this category does if the cache contains cached responses.
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
// | |
// NSMutableURLRequest+CacheControl.m | |
// | |
// Created by Paul Goracke on 2/26/13. | |
// | |
@implementation NSMutableURLRequest (CacheControl) | |
+ (instancetype) newCachePolicyRequestWithURL:(NSURL *)url timeoutInterval:(NSTimeInterval)timeoutInterval { | |
// If we have cached info, tell request to ignore cache because we only want to process data when we get new from server | |
// request mechanism doesn't automatically configure "If-Modified-Since" or "If-None-Match" if we have that info | |
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url | |
cachePolicy:NSURLRequestUseProtocolCachePolicy | |
timeoutInterval:timeoutInterval]; | |
NSURLCache* cache = [NSURLCache sharedURLCache]; | |
NSCachedURLResponse* cachedResponse = [cache cachedResponseForRequest:request]; | |
NSHTTPURLResponse* urlResponse = (NSHTTPURLResponse*)[cachedResponse response]; | |
NSString* lastModified = [[urlResponse allHeaderFields] objectForKey:@"Last-Modified"]; | |
if ( lastModified != nil ) { | |
[request setValue:lastModified forHTTPHeaderField:@"If-Modified-Since"]; | |
// prefer server modification handling over local caching | |
request.cachePolicy = NSURLRequestReloadIgnoringCacheData; | |
} | |
NSString* etag = [[urlResponse allHeaderFields] objectForKey:@"ETag"]; | |
if ( etag != nil ) { | |
[request setValue:etag forHTTPHeaderField:@"If-None-Match"]; | |
// prefer server modification handling over local caching | |
request.cachePolicy = NSURLRequestReloadIgnoringCacheData; | |
} | |
return request; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment