How do I decode html coded characters in an NSString?

11,863

Solution 1

Check out these NSString categories

Solution 2

This solution worked well for me if you're still using Objective C code.

- (NSString *)decodeHtmlStringValue
{
  NSData *encodedString = [self dataUsingEncoding:NSUTF8StringEncoding];
  NSAttributedString *htmlString = [[NSAttributedString alloc] initWithData:encodedString
                                                                    options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
  return [htmlString string];
}

If your using swift

https://stackoverflow.com/questions/25607247/how-do-i-decode-html-entities-in-swift

Solution 3

NSString stringByReplacingPercentEscapesUsingEncoding with the correct string encoding should do the magic.

[yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

might be a good candidate.

Share:
11,863

Related videos on Youtube

luis.ramireznossa
Author by

luis.ramireznossa

Aspiring mobile game developer

Updated on June 04, 2022

Comments

  • luis.ramireznossa
    luis.ramireznossa almost 2 years

    I am writing an app with both english and french support. The app requests information from a server and the server response uses JSON. I am using the JSONKit library to parse the response but the strings its parsing from the french responses look like this:

    Membres –Économisez 5% sur les services et jusqu’à 15% sur d’autres produits

    How do I decode the special characters? so that I get this:

    Membres –Économisez 5% sur les services et jusqu’à 15% sur d’autres produits

    I looked at the API for NSString and tried some of the instance methods but I don't know much about character encodings and I ended up getting some weird results. So if you can also provide a brief explanation on character encodings I'd really appreciate it.

    Thanks in advance

  • luis.ramireznossa
    luis.ramireznossa over 12 years
    I tried: NSString *myString = [myOtherString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEnc‌​oding]; but its returning null. I checked myOtherString and it contains the encoded string.
  • Martin Winter
    Martin Winter about 10 years
    The documentation states: Returns nil if the transformation is not possible, for example, the percent escapes give a byte sequence not legal in encoding.
  • miracle-doh
    miracle-doh over 7 years
    This is for percent decoding, the question is asking for html code decoding