11

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.

  1. 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.

  2. 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?

Community
  • 1
  • 1
lostintranslation
  • 23,756
  • 50
  • 159
  • 262

1 Answers1

0

Just came across the same situation, I just figure out setting value for "Timeout" key can reduce the Unresponding time.

var options = [NSAttributedString.DocumentReadingOptionKey : Any]()
options[.documentType] = NSAttributedString.DocumentType.html
options[.characterEncoding] = String.Encoding.utf8.rawValue
options[.timeout] = 5.0 //Important!You can adjust this value to suitable value.

I think the following line of code always runs in the main queue.There is no way to avoid UI hanging completely while using this function.

NSAttributedString(data: data!, options: options, documentAttributes: nil)
Li Fumin
  • 1,383
  • 2
  • 15
  • 31
  • 1
    `timeout` is only available on AppKit apparently. Not a patch solution for iOS unfortunately.. – DZenBot Mar 05 '20 at 21:39