I am trying to load some html text into an NSAttributedString and I am seeing the UI hang.
Looking around I am not sure if that is possible as its looks like it may have to run on the main thread: NSAttributedString from HTML in the background thread
In swift 3 iOS 10 I am able to 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 couple things.
Not sure why it doesn't crash. But I suspect that its still running on the main thread as the UI still locks up for a few seconds.
There are images in the html. Wondering if that is was is causing most of the delay. I still want to display the images but wondering if I can pull them out and just display the text initially and load the images on a background thread. Not sure if there is anything built into NSAttributedString to pull out images, or doI have to parse them out manually.
Is there any way at all to get this data to load on a background thread so I can not lock up the UI when using an NSAttributedString initialized with html data?