Search code examples
iosjsonencodingutf-8nsstringencoding

How to use stringWithContentsOfFile:usedEncoding:error:


I've tried to load a file with unknown encoding. This is because I dont always have control over the file that I will load. I assumed that the method stringWithContentsOfFile:usedEncoding:error: will do this and will let me know the file encoding. Unfortunately following code doesn't provide the encoding I want - it always return 0.

NSStringEncoding *encoding = nil;
NSError *error = nil;
NSString *json = [NSString stringWithContentsOfFile:path
                                       usedEncoding:encoding
                                              error:&error];
NSLog(@"\n%lu\n%@",(unsigned long)encoding,error);

It returns content of file, so you may wonder why I need this encoding, well that string is JSON that I want to serialize it into NSDictionary and the dataUsingEncoding: method requires encoding. I tried to pass encoding variable but this throws an error. So I tried fail safe UTF8 encoding and then it worked.

    NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];

So I must using this incorrect as encoding equals to 0 instead of 4 (UTF8). Can someone help me with that?


Solution

  • Try that :

    NSStringEncoding encoding;
    NSError *error = nil;
    NSString *json = [NSString stringWithContentsOfFile:path
                                       usedEncoding:&encoding
                                              error:&error];
    NSLog(@"\n%lu\n%@",(unsigned long)encoding,error);
    

    To be clearer, you can't receive the encoding value in your pointer, you need to give a plain NSStringEncoding address