How to Change String Encoding from KOI8-R to UTF8 in Objective-C

No comments on How to Change String Encoding from KOI8-R to UTF8 in Objective-C

Written by

in

KOI8-R is an 8-bit character encoding, designed to cover Russian, which uses the Cyrillic alphabet. I was getting a fileName from IMAP in this encoding and wanted to convert it to normal readable UTF-8.

My question concerning this issue in stackoverflow was banned. I had to solve this myself and spent quite a bit of time.

There is one solution, that works for many encodings – to use CFString methods:

<br />
– (NSString*)decodeKOI8R:(NSString*)stringToDecode {</p>
<p>    CFStringRef aCFString = CFStringCreateWithCString(NULL, [stringToDecode UTF8String], kCFStringEncodingKOI8_R);<br />
    NSString *decodedString = (__bridge NSString*)aCFString;</p>
<p>    return decodedString;<br />
}<br />

But for some reason it worked for UTF-7 but didn’t for KOI8-R.

I searched Google for hours, but couldn’t find a solution. Suddenly, I found a solution in MailCore CTBareAttachment class method, called decodedFilename.

This is ObjC code of that method:

<br />
-(NSString*)decodedName {<br />
    return MailCoreDecodeMIMEPhrase((char *)[self.name UTF8String]);<br />
}<br />

This is a C language method, that converts char* to the NSString with a proper encoding.

<br />
NSString *MailCoreDecodeMIMEPhrase(char *data) {<br />
    int err;<br />
    size_t currToken = 0;<br />
    char *decodedSubject;<br />
    NSString *result;</p>
<p>    if (*data != ‘\0’) {<br />
        err = mailmime_encoded_phrase_parse(DEST_CHARSET, data, strlen(data),<br />
                                            &currToken, DEST_CHARSET, &decodedSubject);</p>
<p>        if (err != MAILIMF_NO_ERROR) {<br />
            if (decodedSubject == NULL)<br />
                free(decodedSubject);<br />
            return nil;<br />
        }<br />
    } else {<br />
        return @””;<br />
    }</p>
<p>    result = [NSString stringWithCString:decodedSubject encoding:NSUTF8StringEncoding];<br />
    free(decodedSubject);<br />
    return result;<br />
}<br />

Here

<br />
#define DEST_CHARSET “UTF-8”<br />

and mailmime_encoded_phrase_parse is a pretty complex method, that is not easy even to copy paste here. So, this problem seems to have no easy solution, except using this C method. Actually this method parses a phrase and calls decoding C method for each word. And I ended up using it.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *