How To Display HTML In UITextView

UITextView has field text which can be only plain text, you can’t put there any style.

It also has attributed text which is much more powerful. NSAttributedString has few constructors, so there are many choices.

Let’s display this:

let htmlString = “<strong>SmashSwift</strong>”

Inside this:

 let textView = UITextView()

do {
    
let htmlText = try NSAttributedString(
          data: htmlString.data(using:
String.Encoding.unicode)!,
          options: [.
documentType: NSAttributedString.DocumentType.html],
          documentAttributes:
nil)
     textView.
attributedText = htmlText
} catch
let error {
     textView.
attributedText = NSAttributedString(string: “Error: \(error)”)
}

Creating NSAttributedString may throw an error, in this case, you will see error inside your TextView.