2

I have some chunks of data that are encoded with random techniques, say first chunk is encoded by NSUTF8StringEncoding another one with NSASCIIStringEncoding or kCFStringEncodingWindowsArabic.

I don't know which chunk is encoded with which type of encoding. I have tried multiple options e.g. if result is nil then decode with NSNonLossyASCIIStringEncoding, but to no avail. Is there any way to determine a specific chunk of data is encoded with type of Encoding ?

Any help will be appreciated.

Muhammad Burhan
  • 145
  • 1
  • 2
  • 11

2 Answers2

0

You can find the answer for your question here: https://stackoverflow.com/a/9836989/2923506

This is a copy&paste code adapted to ARC of the user MiiChiel, because it's a good answer. "if ASCII and UTF8 give both a string in return. For instance: UTF8 gives me some extra characters (negative result) and ASCII are showing the right characters (positive result)."

NSString *responseString, *responseStringASCII, *responseStringUTF8;

responseStringASCII = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]; 
if (!responseStringASCII)
{
   // ASCII is not working, will try utf-8!

    responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}
else
{
    //  ASCII is working, but check if UTF8 gives less characters

    responseStringUTF8  = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    if(responseStringUTF8 != nil && [responseStringUTF8 length] < [responseStringASCII length])
    {
        responseString  =   [responseStringUTF8 retain];
    }
    else 
    {
        responseString  =   [responseStringASCII retain];
    }

}

I hope this can help you.

Community
  • 1
  • 1
J. Lopes
  • 1,336
  • 16
  • 27
0

Objective C includes a built-in way to detect a the encoding of a string embedded in NSData.

(Note, if your case you still need to partition each chunk into a separate NSData objects.)

NSData* data = // Assign your NSData object...

NSString* string;
NSStringEncoding encoding = [NSString stringEncodingForData:data encodingOptions:nil convertedString:&string usedLossyConversion:nil];
Andrew Rondeau
  • 667
  • 7
  • 18