如何在 Swift 3 中解码 html 格式的文本

How to decode html formatted text in Swift 3

我想在 iOS 应用中显示以下 html 文本

<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>

我尝试使用 NSAttributedString 并在 html 字符串中附加字体,但是没有任何效果

let st:String = pjt.value(forKey: "description") as! String // Original content from API - "&lt;p&gt;&lt;span style=&quot;color: #000000;&quot;&gt;Experience royalty in all its splendor&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: #000000;&quot;&gt; An address that is a possession of pride&lt;/span&gt;&lt;/p&gt;&lt;........"

let desc:Data = st.data(using: String.Encoding.utf8, allowLossyConversion: true)!
                //st.data(using: String.Encoding.utf16)!
            do {
                let attrStr = try NSAttributedString(data: desc, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
                print("Attr STr \(attrStr)")
                self.textView.attributedText = attrStr;
            }

self.webView.loadHTMLString(st, baseURL: nil)

的网络视图中也无法正常工作

已更新

Textview 或 webview 或标签都显示相同的普通 html 字符串 <p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>

有什么帮助吗?

: Swift 3

谢谢!

你的字符串是

"&lt;p&gt;&lt;span style=&quot;color: #000000;&quot;&gt;Experience royalty in all its splendor&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: #000000;&quot;&gt; An address that is a possession of pride&lt;/span&gt;&lt;/p&gt;"

所有 HTML 标记编码为 HTML 实体。字符串必须转换为

<p><span style="color: #000000;">Experience royalty in all its splendor</span><br /><span style="color: #000000;"> An address that is a possession of pride</span></p>

before 将其传递给属性字符串。这可以例如 使用 How do I decode HTML entities in swift?:

中的 stringByDecodingHTMLEntities 方法完成
let st  = (pjt.value(forKey: "description") as! String).stringByDecodingHTMLEntities

(与您当前的问题无关:强制转换 as! String 如果该值不存在或不是字符串,则可能会在运行时崩溃。 您应该改用可选绑定。)