NSAttributed string from html without user interface thread hanging

I am trying to load some html text into an NSAttributedString and I can see that the user interface is hanging.

Looking back, I'm not sure if this is possible, since it looks like it can be run in the main thread: NSAttributedString from HTML in the background thread

In swift 3 iOS 10 I can run this without exception

let myString = // some html content DispatchQueue.global(qos: .background).async { let data = myString.data(using: .utf8) let options: [String: Any] = [ NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue ] do { let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil) DispatchQueue.main.async { () -> Void in self.label.attributedText = attributedString } } catch let error as NSError { print(error.localizedDescription) } } 

A few things.

  • Not sure why this is not a glitch. But I suspect that it is still running on the main thread, as the user interface is still blocked for a few seconds.

  • There are images in html. Surprising, if it was, causes most of the delay. I still want to display the images, but I wonder if I can pull them out and just display the text initially and load the images in the background stream. Not sure if NSAttributedString has anything to pull out images, or doI need to parse them manually.

Is it even possible to load this data into a background thread so that I cannot block the user interface when using NSAttributedString initialized with html data?

+5
source share

Source: https://habr.com/ru/post/1257664/


All Articles