1

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?

Lukasz 'Severiaan' Grela
  • 6,078
  • 7
  • 43
  • 79

2 Answers2

3

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

gbitaudeau
  • 2,207
  • 1
  • 17
  • 13
1

Since you are not aware of the encoding of the file, I will suggest you to see this link. Its basically String Programming Guide which will let you know in depth what to do.

Below is the snapshot for which you are looking into:

enter image description here

Hope this will help you. Happy coding :)

Shubhendu
  • 1,081
  • 8
  • 13