views:

200

answers:

3

I am fairly new to iphone development and programming in general and am wondering how to read some text from a text file to be diplayed in a UITextView. I have tried various ways to do it but just can't seem to be able to get it to display:

- (void)viewDidLoad {
[super viewDidLoad];

NSString *filePath=[[NSBundle mainBundle] pathForResource:@"untitled" ofType:@"txt"];

NSString *someText=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
textView.text=someText;

Some sample code would be greatly appreciated. Thanks in advance

+1  A: 

You shouldn't include the extension in the pathForResource: parameter:

[[NSBundle mainBundle] pathForResource:@"untitled.txt" ofType:@"txt"]

should be

[[NSBundle mainBundle] pathForResource:@"untitled" ofType:@"txt"].

Benedict Cohen
ok, I have tried that and it still doesn't work
Felixs
A: 

Is untitled.txt actually where you think it is? Try logging filePath and see if it's what you expect. (You could do [[NSFileManager defaultManager] isReadableFileAtPath:filePath] to be completely certain.)

If the path is correct then the problem must be with loading the text. One such problem could be that the file is not encoded in UTF8. Mike Ash recently blogged about character encoding. At the end of the post he describes how to handle text files of unknown encoding.

Benedict Cohen
I had created untitled.txt just as a sample to see if this worked. I have checked and it is in UTF8. Putting in a few if statements, it seems that it is something to do with the file path. The file was created in Xcode in the resources folder.
Felixs
+1  A: 

I had to change the name of the text file to 'untitled.txt' from just plain 'untitled' in Xcode. It was a text file but didn't have the extension of .txt. This doesn't seem to be automatically appended if you create the text file in Xcode.

Felixs