问题
In some cases, I really need to know a file's encoding while reading the file. Sometimes we can do as Apple's String Programming Guide suggest :
Reading data with an unknown encoding
If you find yourself with text of unknown encoding, it is best to make sure that there is a mechanism for correcting the inevitable errors. For example, Apple's Mail and Safari applications have encoding menus, and TextEdit allows the user to reopen the file with an explicitly specified encoding.
If you are forced to guess the encoding (and note that in the absence of explicit information, it is a guess):
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 are coming from.
Finally, you can try NSAttributedString's loading methods from the Application Kit (such as initWithURL:options:documentAttributes:error:).
These methods attempt to load plain text files, and return the encoding used. They can be used on more-or-less arbitrary text documents, and are worth considering if your application has no special expertise in text. They might not be as appropriate for Foundation-level tools or documents that are not natural-language text.
Here I came into some problem. Sometimes I can know the error. For example when I read a GB2312 encoding file using UTF8 way, then I will get nil, so I know the error. But when I read GB2312 encoding file using BIG5 way, I can't know the error.
NSAttributedString's init method may work on Mac, but when it comes to iOS, it needs iOS7, not so good.
I also search for it and find some discussing about it like this on cocoabuilder, but also on Mac. Then how about on iOS?
回答1:
You can use stringWithContentsOfFile:usedEncoding:error:, which returns, in addition to the new string, the encoding that was used.
But you won't be always able to determine the encoding for the file.
来源:https://stackoverflow.com/questions/18851558/ios-whats-the-best-way-to-detect-a-files-encoding