[SWIFT] How to convert HTML using NSAttributedString

This tutorial will show you how to convert HTML using NSAttributedString. By convert HTML using NSAttributedString, I mean converting HTML tags and creating an attributed string from it. Then loading it to a text component like UILabel or UITextView. Probably you will get a response from an API sometimes where you will have a string together with all the HTML tags in it, and you would need to present it to the UI in an attributed string.

HTML Example

<!DOCTYPE html>

<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>


Creating the Extension

I am using extensions a lot and would advise you the same, as they are the key to organizing your Swift code and making your functions reusable. Now, we are going to create the string extension where we will keep our convertHtml() function that will do all the job for us. This function will convert all the HTML tags into NSAttributedString. Let’s name the extension String+Extensions.swift.

extension String{    
    func convertHtml() -> NSAttributedString{
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
            return NSAttributedString()
Recommended post: I ❤ Swift [Part 1] – UIViewController & Extensions

How to Use?

Finally, I will create a string out of the HTML Example and call convertHtml() which will make it an NSAttributedString. Then, I will add the result to a UILabel with a name descLbl.

descLbl.attributedText = "<!DOCTYPE html><html><body><h1>This is heading 1</h1><h2>This is heading 2</h2><h3>This is heading 3</h3><h4>This is heading 4</h4><h5>This is heading 5</h5><h6>This is heading 6</h6></body></html>".convertHtml()

Here is the final output of our UILabel:



I hope that you enjoyed this tutorial and that it helped you learn something new. Don’t forget to share and help others, or leave a comment in the comments section if you have any issue with this approach.

Leave a Reply

Your email address will not be published. Required fields are marked *