Cache files locally on iPhone

i have this project that may now and then get some big xml files…in order to make life a little easier for the user, i am opting to cache these suckers by writing the files to the Documents directory of my app. Here is how i am “caching” xml.

 

#import "RootViewController.h"
 
#define FILENAME @"xmlData.xml"
#define FILEGETKEY @"coordinates"
@interface RootViewController()
+ (NSString *)dataFilePath;
@end
 
@implementation RootViewController
 
 
#pragma mark -
#pragma mark View lifecycle
 
 
- (void)getXmlPlease {
 
 
	//set the hook
	isGoodToWrite = NO;
 
	//our data objec to store/read from the xml
	NSData *dataobject;
 
	//cehck if we have the xml already
	NSFileManager *fileManager = [NSFileManager defaultManager];
	BOOL isFileExists = [fileManager fileExistsAtPath:[RootViewController dataFilePath]];
 
	NSLog(@"%d : existing @ %@",isFileExists,[RootViewController dataFilePath]);
 
	if (!isFileExists) {//we need to "cache" this data (xml)
		NSString *pathToRemoteData = @"http://www.aurl.com/filename.xml";
		dataobject = [NSData dataWithContentsOfURL:[NSURL URLWithString:pathToRemoteData]];
 
		//cache it for next time
		[fileManager createFileAtPath:[RootViewController dataFilePath] contents:dataobject attributes:nil];
 
 
	}else {//we already have this from a previous time
 
		dataobject = [fileManager contentsAtPath:[RootViewController dataFilePath]];
	}
 
	NSXMLParser *parser =[[NSXMLParser alloc] initWithData:dataobject];
	[parser setDelegate:self];
	[parser parse];
}
+ (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths objectAtIndex:0];
    return [docDirectory stringByAppendingPathComponent:FILENAME];
}
 
#pragma mark -
#pragma mark NSXMLParser
//do parsing code
 
@end

I am fortunate that i don’t have to think about replacing or writing over these files. It would be just a bit more code to do so, but i wanted to document the simplest solution i found today