2014年4月10日 星期四

How To Read a File From Your Application Bundle

http://iphoneincubator.com/blog/data-management/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. }  

沒有留言:

張貼留言