NSAttributedString initWithData and NSHTMLTextDocumentType crash if not on main thread

前端 未结 2 1112
栀梦
栀梦 2020-12-14 11:36

calling

NSAttributedString * as = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocume         


        
相关标签:
2条回答
  • 2020-12-14 12:01

    The documentation is pretty explicit about that.

    The HTML importer should not be called from a background thread (that is, the options dictionary includes NSDocumentTypeDocumentAttribute with a value of NSHTMLTextDocumentType). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

    Using the HTML importer (NSHTMLTextDocumentType) is only possible on the main thread.

    (Source: Apple's documentation)

    0 讨论(0)
  • 2020-12-14 12:01

    Maybe its too late to answer this question, but may help others.

    Actually NSAttributedString and NSHTMLTextDocumentType must run asynchronously either on main queue or a global queue.

    You can use it in a background thread but you have to dispatch your code block containing NSAttributedString's initializer on a global or main queue. For example:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
    
    
    
    
                print("Started on \(NSThread.currentThread())")
    
                let encodedData = "<font color=\"red\">Hello</font>".dataUsingEncoding(NSUTF8StringEncoding)!
                let attributedOptions : [String: AnyObject] = [
                    NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                    NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
                ]
    
    
                let attributedString = (try? NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) ?? NSAttributedString(string: ""))
    
    
    
                print("Finished")
    
            }
    
    0 讨论(0)
提交回复
热议问题