Ali Hamad Ali Hamad - 4 years ago 139
Swift Question

showing html content in TextView efficiently

I'm using this way and it works fine, but has a slowness fallback because of the usage of NSHTMLTextDocumentType as i did my research

do {

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

let date = html.data(using: String.Encoding.utf8, allowLossyConversion: true)!

return try NSAttributedString(data: data, options: attributedOptions , documentAttributes: nil)

} catch let error as NSError {

print("htmo2String \(error)")
}


any ideas how to do it faster or another efficient way to do it!

Answer Source

Maybe you can execute the parse code on a queue...

func parse(_ html: String, completionHandler: @escaping (_ attributedText: NSAttributedString?) -> (Void)) -> Void
{
    let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false)

    let options: [String: AnyObject] = [
        NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType as AnyObject
    ]

    completionHandler(try? NSAttributedString(data: htmlData!, options: options, documentAttributes: nil))
}

And now call the function and wait from response...

let queue: DispatchQueue = DispatchQueue(label: "com.yourcompany.Process./html_converter")

queue.async
{
    parse("<p>¡Hola mundo</p>", completionHandler: { (attributtedString: NSAttributedString?) -> (Void) in 
        if let attributtedString = attributtedString
        {
            DispatchQueue.main.async
            {
                print("str:: \(attributtedString)")
            }
        }
    })
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download