Is there a way to "automatically detect" the encoding of a resource when loading with stringFromContentsOfURL?

Is there a way to "automatically detect" the encoding of a resource when loading with stringFromContentsOfURL? The current (unallocated) method + (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;requires URL encoding. I noticed that making a mistake is what I want to do. Is there any way to check this somehow and always right? (I am using UTF8 now.)

+3
source share
2 answers

I would try this function from the docs

Returns a string created by reading data from a given URL and returns the encoding used to interpret the data by reference.

+ (id)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error

this seems to guess the encoding and then returns it to you

+4

, ( ) , - . ( ) , ASCII UTF-8, UTF-16. , , NSWindowsCP1252StringEncoding, . , NSData, . :

NSData * urlData = [NSData dataWithContentsOfURL:aURL];
NSString * theString = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
if (!theString) {
    theString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
if (!theString) {
    theString = [[NSString alloc] initWithData:urlData encoding:NSUTF16StringEncoding];
}
if (!theString) {
    theString = [[NSString alloc] initWithData:urlData NSWindowsCP1252StringEncoding];
}
// ...
// use theString here...
// ...
[theString release];
+2

Source: https://habr.com/ru/post/1598132/


All Articles