GitHub Jobs API course. Convert HTML to NSAttributedString. Lesson 5.

GitHub Jobs API course. Convert HTML to NSAttributedString. Lesson 5.

When you're working on a mobile app you may encounter an issue when your backend will return an HTML text.

The one reliable method to parse HTML into your app is to convert HTML to NSAttributedString.

The basic trick of the parsing HTML text into NSAttributesString is this piece of code:

Create variable let data ​= Data(html.utf8)

And after that convert your data to NSAttributed string:

if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
    yourLabel.attributedText = attributedString
}

One important part of parsing HTML is to make sure that you specify html.utf8 and in your options dictionary make sure that you also specify string encoding like this:

        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html,

                                                                           

             .characterEncoding: String.Encoding.utf8.rawValue]

It's very important that you specify  .characterEncoding: String.Encoding.utf8.rawValue with utf8 encoding as well.

And here's the code for the method that I am utilizing to convert HTML text either in viewDidLoad or didSet when I am parsing JSON into my app.

func convertHTML(text: String, attributedText: inout NSAttributedString) -> NSAttributedString {

        let data ​= Data(text.utf8)

        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html,

                                                                           

             .characterEncoding: String.Encoding.utf8.rawValue]

        

        if let attributedString = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) {

            attributedText = attributedString

            return attributedString

        }

        return attributedText

    }

                                      

In this lesson, I am utilizing this approach and using it in my method to convert HTML.

What is covered in this lesson:

  • inout
  • NSAttributedString
  • How to convert HTML text into NSAttributedString

Resources:



To view or add a comment, sign in

More articles by Eugene Berezin, Psy.M, CHt

Others also viewed

Explore content categories