I have a string containing HTML. I would like to display the HTML in a TextView control. I found some code and tried it:
def = "some html text"
definition.attributedText = NSAttributedString(
data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
On the option I get an error:
[String: String] is not convertible to string.
Can someone help me display HTML in a TextView?
htmlToTextView. setText(HtmlCompat. fromHtml(htmlText, 0)); In the above code we are taking HTML data from fromHtml() and appending to textview using setText() .
In Android, we usually need HTML files for displaying the content in WebView. If the developer wants to add any website page or want to create a local webpage for the app then it could be done using HTML files.
This works for me. Remember that the NSAttributedString
constructor now throws
an NSError
object:
Swift 3:
do {
let str = try NSAttributedString(data: def.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
print(error)
}
Swift 2.x:
do {
let str = try NSAttributedString(data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With