Here is some code which I use to pull a text file into a UITextView
called textView
.
Because I can't always know the file's encoding ahead of time, I use the method -stringWithContentsOfFile:usedEncoding:error:
, which stores an encoding value by reference.
Once I have the encoding, I then open up the file and, if there's an error, print out some information:
NSError *_error = nil;
NSStringEncoding _textEncoding;
NSString *_contentText = [NSString stringWithContentsOfFile:[baseURL path] usedEncoding:&_textEncoding error:&_error];
if (_error) {
NSLog(@" _error: %@", [_error userInfo]);
NSLog(@" _textEncoding: %d", _textEncoding);
}
textView.text = _contentText;
On an iPhone, if the file is UTF8-encoded, the text view displays the file's contents properly.
On an iPhone, if a file is ASCII-encoded (NSASCIIStringEncoding
), then I get a strange string encoding value:
2010-07-23 02:57:46.786 App[9160:307] _error: {
NSFilePath = "/var/mobile/Applications/0AD83E02-7A2A-4665-8B8F-17E03EE12B9E/Documents/A+B.txt";
}
2010-07-23 02:57:46.791 App[9160:307] _textEncoding: 805298632
For NSASCIIStringEncoding
I should get a value of 1, not 805298632.
The twist is that, if I open the file through the Simulator, I get the correct encoding value and the text view displays the ASCII-encoded file's contents.
I think I have the correct syntax, but I guess I have missed something, possibly obvious. What am I doing wrong here?