我一直在研究一个 SOAP Web 服务,它使用 Caché 来避免以前完成的 HTTP 请求。
当我尝试将我的 NSDictionary 保存到文件时出现错误(我猜这是因为它不遵循属性列表结构)并且我知道如何修复它。
这是我的代码:
[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];
}
加载缓存功能:
- (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];
}
保存缓存功能:
- (void)saveCache {
NSString* docsurl = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
docsurl = [docsurl stringByAppendingPathComponent:@"cache.txt"];
if ([_cache writeToFile:docsurl atomically:YES]) {
NSLog(@"SAVED");
} else {
NSLog(@"ERROR");
}
}