luis.ramireznossa
luis.ramireznossa

Reputation: 261

How do I decode html coded characters in an NSString?

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

Upvotes: 4

Views: 12132

Answers (3)

StackRunner
StackRunner

Reputation: 1503

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

Upvotes: 5

cellcortex
cellcortex

Reputation: 3176

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

[yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

might be a good candidate.

Upvotes: 1

Alastair Stuart
Alastair Stuart

Reputation: 4185

Check out these NSString categories

Upvotes: 3

Related Questions