开发者

How do I decode html coded characters in an NSString?

开发者 https://www.devze.com 2023-04-06 13:50 出处:网络
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 str

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 k开发者_JS百科now 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


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


Check out these NSString categories


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

[yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

might be a good candidate.

0

精彩评论

暂无评论...
验证码 换一张
取 消