Gopik
Gopik

Reputation: 255

How to decode html formatted text in Swift 3

I want to display the below html text in iOS app

<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>

I tried with NSAttributedString and appending font in html string, however nothing works

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;
            }

It's also not working in web view with self.webView.loadHTMLString(st, baseURL: nil)

Updated

Textview or webview or label all shows the same plain html string <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>

Any help?

Note: Swift 3

Thanks!

Upvotes: 0

Views: 2000

Answers (1)

Martin R
Martin R

Reputation: 539685

Your string is

"&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;"

with all HTML markup encoded as HTML entities. The string must be transformed to

<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 passing it to the attributed string. This can for example be done using the stringByDecodingHTMLEntities method from How do I decode HTML entities in swift?:

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

(Unrelated to your current problem: the forced cast as! String can crash at runtime, if the value is not present or not a string. You should use optional binding instead.)

Upvotes: 2

Related Questions