4

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

2

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

Check out these NSString categories

2 Comments

How would I go about using this? Probably a dumb question but I'm still fairly new to iPhone programming
Add that file and its matching h header file to your project. NSString will then have a new instance method called stringByDecodingHTMLEntities. NSString *decodedString = [encodedString stringByDecodingHTMLEntities];
1

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

[yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

might be a good candidate.

3 Comments

I tried: NSString *myString = [myOtherString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; but its returning null. I checked myOtherString and it contains the encoded string.
The documentation states: Returns nil if the transformation is not possible, for example, the percent escapes give a byte sequence not legal in encoding.
This is for percent decoding, the question is asking for html code decoding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.