How to cache xml lists downloaded from a server?
I am trying to figure out how to cache a list of comic titles that I want to use in a uitableview, and will be updated roughly every week, so instead of loading the list every time the app is launched from the web-server I want to hold onto a cache.. only problem is I'm finding the documentation hard to come across for caching lists like this.
Any example code or suggestions wo开发者_Go百科uld be greatly appreciated :)
- You fetch the XML
- You parse it to a NSDictionary using NSXMLParser
- You serialize and store the dictionary.
@implementation NSDictionary(BinaryPlist)
- (BOOL)writeToBinaryFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile {
NSString *errorString = nil;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:self format:NSPropertyListBinaryFormat_v1_0
errorDescription:&errorString];
if (errorString) {
return NO;
}
return [data writeToFile:path atomically:useAuxiliaryFile];
}
@end
- Then you can define for how long you should consider the cache fresh, or, alternatively, issue HTTP HEAD request and check the Last-Modified header.
- (BOOL)cacheValid:(NSString*)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSDictionary *attrs = [fileManager attributesOfItemAtPath:path error:&error];
if (!error) {
NSDate *modDate = [attrs fileModificationDate];
NSTimeInterval delta = - [modDate timeIntervalSinceNow];
if (delta < kCacheTTL) {
return YES;
}
}
return NO;
}
精彩评论