Skip to content

Instantly share code, notes, and snippets.

@AquaGeek
Created October 7, 2011 18:49
Show Gist options
  • Save AquaGeek/1271066 to your computer and use it in GitHub Desktop.
Save AquaGeek/1271066 to your computer and use it in GitHub Desktop.
NSCachedURLResponse and NSKeyedArchiver issue
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSLog(@"Hello, World!");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com"]];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"Testing" forKey:@"A test"];
NSCachedURLResponse *cachedResp = [[NSCachedURLResponse alloc] initWithResponse:response
data:data
userInfo:userInfo
storagePolicy:NSURLCacheStorageAllowed];
NSString *filePath = [@"~/Desktop/test" stringByExpandingTildeInPath];
[NSKeyedArchiver archiveRootObject:cachedResp toFile:filePath];
// Try to unarchive it
NSCachedURLResponse *retrievedResp = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"Response: %@", [retrievedResp response]);
NSLog(@"Data: %@", [retrievedResp data]);
NSLog(@"User info: %@", [retrievedResp userInfo]);
NSLog(@"Cache policy: %lu", [retrievedResp storagePolicy]);
[pool drain];
return 0;
}
@implementation NSCachedURLResponse(HackityHack)
- (id)initWithCoder:(NSCoder *)aDecoder
{
return [self initWithResponse:[aDecoder decodeObjectForKey:@"response"]
data:[aDecoder decodeObjectForKey:@"data"]
userInfo:[aDecoder decodeObjectForKey:@"userInfo"]
storagePolicy:(NSURLCacheStoragePolicy)[aDecoder decodeIntForKey:@"storagePolicy"]];
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:[self response] forKey:@"response"];
[aCoder encodeObject:[self data] forKey:@"data"];
[aCoder encodeObject:[self userInfo] forKey:@"userInfo"];
[aCoder encodeInt:[self storagePolicy] forKey:@"storagePolicy"];
}
@end
@darrarski
Copy link

Any idea how to force NSURLResponse.userInfo dict to be stored on disk when using NSURLCache? It looks like NSURLCache is not calling encodeWithCoder and userInfo is lost when response in saved in disk cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment