I have been working on a SOAP Web Service that uses a Caché to avoid HTTP requests when they have been done before.
When I try to save my NSDictionary to a file I get a error (I guess it is because it doesn’t follow the Properties List structure) and I know how to fix it.
This is my code:
[self loadCache];
NSData *responseData;
NSMutableDictionary* dict = [_cache objectForKey:delegate.type];
if (dict != nil && [dict objectForKey:request.HTTPBody] != nil ) {
responseData = [dict objectForKey:request.HTTPBody];
} else {
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (dict == nil) {
dict = [[NSMutableDictionary alloc] init];
[_cache setObject:dict forKey:delegate.type];
[dict setObject:[NSNumber numberWithDouble:NSTimeIntervalSince1970] forKey:@"FECHA"];
}
if (responseData == nil) {
responseData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"xml"]];
}
NSLog(@"%@", [[request.HTTPBody copy] class]);
[dict setObject:responseData forKey:request.HTTPBody];
[self saveCache];
}
loadCache Function:
- (void)loadCache {
if (_loadedCache) return;
NSString* docsurl = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
docsurl = [docsurl stringByAppendingPathComponent:@"cache.txt"];
_cache = [[NSMutableDictionary alloc] initWithContentsOfFile:docsurl];
if (_cache == nil) _cache = [[NSMutableDictionary alloc] init];
}
saveCache Function:
- (void)saveCache {
NSString* docsurl = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
docsurl = [docsurl stringByAppendingPathComponent:@"cache.txt"];
if ([_cache writeToFile:docsurl atomically:YES]) {
NSLog(@"SAVED");
} else {
NSLog(@"ERROR");
}
}
As commented: Solved! I was trying to use NSData as KEY, and it can only be used as VALUE.