iphoneiosencodingutf-8nsstring

NSString from text file with unknown encoding


I'm trying to show content of text file with unknown encoding according to Apple's documentation:

Try stringWithContentsOfFile:usedEncoding:error: or initWithContentsOfFile:usedEncoding:error: (or the URL-based equivalents). These methods try to determine the encoding of the resource, and if successful return by reference the encoding used.

If (1) fails, try to read the resource by specifying UTF-8 as the encoding.

If (2) fails, try an appropriate legacy encoding. "Appropriate" here depends a bit on circumstances; it might be the default C string encoding, it might be ISO or Windows Latin 1, or something else, depending on where your data is coming from.

This is not always working. Is there more reliable ways to detect encoding?


Solution

  • If you do not know the encoding of the data ahead of time, then it has to be guessed through analysis of the raw data, and that can sometimes lead to wrong guesses and thus unreliable decoding. When in doubt, just ask the user which encoding to use.