[英]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. 应用程序从服务器请求信息,服务器响应使用JSON。 I am using the JSONKit library to parse the response but the strings its parsing from the french responses look like this: 我正在使用JSONKit库来解析响应,但是从法语响应中解析的字符串如下所示:
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 Membres-Économisez5%sur les services etjusqu'à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. 我查看了NSString的API并尝试了一些实例方法,但我对字符编码知之甚少,最后得到了一些奇怪的结果。 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. 如果你仍在使用Objective C代码,这个解决方案对我来说效果很好。
- (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 如果你使用swift
https://stackoverflow.com/questions/25607247/how-do-i-decode-html-entities-in-swift https://stackoverflow.com/questions/25607247/how-do-i-decode-html-entities-in-swift
NSString stringByReplacingPercentEscapesUsingEncoding with the correct string encoding should do the magic. 使用正确的字符串编码的NSString stringByReplacingPercentEscapesUsingEncoding应该具有魔力。
[yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
might be a good candidate. 可能是一个很好的候选人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.