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

时间:2017-08-06 06:18:14

标签: ios swift3 uitextview nsattributedstring

我想在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或label all显示相同的普通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

谢谢!

1 个答案:

答案 0 :(得分:2)

你的字符串是

"&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>
之前

将其传递给属性字符串。例如,这可以 使用How do I decode HTML entities in swift?中的stringByDecodingHTMLEntities方法完成:

let st  = (pjt.value(forKey: "description") as! String).stringByDecodingHTMLEntities

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