iOS - Bundle app with text file
cocoa-touch, ios
Solution
If your file will always be read-only (only updated as part of an app update), then add the file to your app's resources in your project. Then you simply read the file from the app's bundle:
// assume a filename of file.txt. Update as needed
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
If you need to provide an initial file with your app but make updates during runtime then you need to package the file like above, but the first time your app is run you need to copy the file to another, writable location in your app's sandbox.
// Get the Application Support directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportDirectory = [paths objectAtIndex:0];
// Create this path in the app sandbox (it doesn't exist by default)
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:appSupportDirectory withIntermediateDirectories:YES attributes:nil error:nil];
// Copy the file from the app bundle to the application support directory
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSString *newPath = [appSupportDirectory stringByAppendingPathComponent:[filePath lastPathComponent]];
[fileManager copyItemAtPath:filePath toPath:newPath error:nil];
Problem
I have a .json file that I want to be bundled with my application as a resource. I've read the File System Programming Guide which says that you should put support files in the `<Application_Home>/Library/Application Support`. So how do I put my .json file in this directory before building my application? And how would I reference the file during runtime?