Swift: Display HTML data in a label or textView

Talha Ahmad Khan picture Talha Ahmad Khan · May 5, 2016 · Viewed 104.8k times · Source

I have some HTML data, which contains headings, paragraphs , images and lists tags.

Is there a way to display this data in one UITextView or UILabel?

Answer

Roger Carvalho picture Roger Carvalho · Nov 10, 2017

For Swift 5:

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

Then, whenever you want to put HTML text in a UITextView use:

textView.attributedText = htmlText.htmlToAttributedString