Five on Friday Use Relative Paths When Adding Frameworks
Apr 07

First you need to add your file to the Resources folder of your Xcode project. Then you can access the file like this (assuming the file is called MyFile.txt):

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
	// do something useful
}

Here’s a complete example reading a help text file into a UIWebView.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HelpDoc" ofType:@"htm"];
NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
if (htmlData) {
	[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]];
}

If you want to read the file into a string, which you can then display in a UITextView, for example, then do this:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];
if (filePath) {
	NSString *myText = [NSString stringWithContentsOfFile:filePath];
	if (myText) {
		textView.text= myText;
	}
}

written by Nick \\ tags: , , ,

2 Responses to “How To Read a File From Your Application Bundle”

  1. Ben Chatelain Says:

    It is possible to add a file to a bundle at runtime? I’m working on an app that downloads a file from the web and I’d like to save it to the iPhone’s file system within the app’s sandbox for later use.

  2. Nick Dalton Says:

    Ben,

    It’s not possible (or at least strongly discouraged) to update files in the app bundle.

    If you’re downloading files and want to store them on the device you should use the Documents directory. You can get the path to this directory with:

    - (NSString *)getDocumentsDirectory {
    	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    	return [paths objectAtIndex:0];
    }
    

Leave a Reply