ƒernando Valle ƒernando Valle - 7 months ago 46
Swift Question

How to minimize time conversion html to NSAttributedString

Hello I am using the following code in order to convert html to NSAttributtedString. My problem is that it takes long time the first time that I executed it:

var html = "<b>Whatever...</b>"
var attributedText = try! NSMutableAttributedString(
data: html.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)

When I perform the conversion for the first time, it takes long time executing. The followed executions takes less time. There is any way to decrease this long first execution?
I thought about execute this code in background at the begining of my app execution but I want to know if there is other smart solution or library the I should import.


use "String.Encoding.utf8" instead of "String.Encoding.unicode" this might reduce your conversion time

var html = "<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!"

let attributedOptions: [String: Any] = [
                    NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                    NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue

var attrString = try! NSAttributedString(data: html.data(using: String.Encoding.utf8)!, options: attributedOptions, documentAttributes: nil)
YOUR_TEXT_VIEW.attributedText = attrString