How to convert HTML to NSAttributedString in SwiftUI ?
Sometimes we get data from API is not always smooth. There is only data that is obtained containing HTML tags. I will share with you how to convert HTML using NSAttributedString. I mean converting HTML tags and creating an attributed string from it. Then load it to a text component like UILabel or UITextView.
HTML tags Example from API
We find in the picture above there is an HTML tag that is&rdquo which should when we display it in our iPhone UI there must be quotes (“ “) . So we must convert this using NSAttributedString.
Create The Extension
You can use extensions to make this. So it can be easy for you to organizing your Swift code and making your functions reusable. Now, we try to create an HTML to string file in your swift and create two extensions.
First, you make a data extension :
Then you make a string extension :
when you can see in your file like this :
This first extension is used to convert the text you want to omit HTML tags using NSAttributedString. This extension itself uses a data format, so we need to convert it from string to data first, which is happens in the second extension. After that, we use the second extension to convert it back into a String. The result of this string can be used by a UILabel or a UITextView. Because they can’t read in data format.
How to use?
After the extensions are created, we add this extension in your UITextView and call html2string to get String from conversion. The code is like below
Here is final output from your conversion
But we have problem with our extension 🥲
We are happy to have succeeded in converting HTML tags into strings. But we have a problem with the change process. This is because The HTML importer should not be called from a background thread.
It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs).
So we can try to solve it using DispatchQueue to make your code asynchronous. The code is like below :
Here we make an empty string to assign the result from conversion. The conversion process we add in onAppear so that before UI called, we can process in Asynchronous. Then we call in our UITextView.
So Far So Good,
That’s my tutorial, and hope you can enjoy it with this. Please 👏 or share this story so others like you can find it. Thank you! 🙋🏻♂️