Created
October 7, 2011 18:49
-
-
Save AquaGeek/1271066 to your computer and use it in GitHub Desktop.
NSCachedURLResponse and NSKeyedArchiver issue
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
#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; | |
} |
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
@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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any idea how to force
NSURLResponse.userInfo
dict to be stored on disk when usingNSURLCache
? It looks like NSURLCache is not callingencodeWithCoder
anduserInfo
is lost when response in saved in disk cache.