Swift: Display HTML data in a label or textView Swift: Display HTML data in a label or textView ios ios

Swift: Display HTML data in a label or textView


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


Here is a Swift 3 version:

private func getHtmlLabel(text: String) -> UILabel {    let label = UILabel()    label.numberOfLines = 0    label.lineBreakMode = .byWordWrapping    label.attributedString = stringFromHtml(string: text)    return label}private func stringFromHtml(string: String) -> NSAttributedString? {    do {        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)        if let d = data {            let str = try NSAttributedString(data: d,                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],                                             documentAttributes: nil)            return str        }    } catch {    }    return nil}

I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.


Add this extension to convert your html code to a regular string:

    extension String {        var html2AttributedString: NSAttributedString? {            guard                let data = dataUsingEncoding(NSUTF8StringEncoding)            else { return nil }            do {                return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)            } catch let error as NSError {                print(error.localizedDescription)                return  nil            }        }        var html2String: String {            return html2AttributedString?.string ?? ""        }}

And then you show your String inside an UITextView Or UILabel

textView.text = yourString.html2String or

label.text = yourString.html2String