Reputation: 255
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 - "<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><........"
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
Reputation: 539685
Your string is
"<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>"
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