Tuesday, October 5, 2010

How To Read a File From Your Application Bundle

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):

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

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

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

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

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];
  2. if (filePath) {
  3. NSString *myText = [NSString stringWithContentsOfFile:filePath];
  4. if (myText) {
  5. textView.text= myText;
  6. }
  7. }

Or simply
use this..

NSString *fileContents = [NSString stringWithContentsOfFile:@"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:@"\n"];



Like Us On Facebook and Receive All Updates!

You can also receive Free Email Updates:

Powered By Tutorails