使用NSAttributedString初始化 html 文本時(shí)(NSHTMLTextDocumentType)會(huì)導(dǎo)致主線程卡死示惊。這應(yīng)該是蘋(píng)果的解析 html 文本的一個(gè) bug酣难。
NSAttributedString.init(data:(string?.data(using:.unicode))!,options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
按照蘋(píng)果文檔的說(shuō)法,上述代碼不可以運(yùn)行在后臺(tái)線程(background thread)筷畦,其次败匹,它會(huì)出現(xiàn) time out 超時(shí)早像,運(yùn)行在主線程會(huì)造成線程卡死。
所以最正確做法應(yīng)該是通過(guò) global queue進(jìn)行初始化掠归,然后將結(jié)果丟回主線程刷新 ui缅叠。
DispatchQueue.global().async {
let text = try? NSAttributedString(data: contentToDisplay.data(using: .unicode)!,
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes:nil)
DispatchQueue.main.async {
strongSelf.contentLabel.attributedText = text
}
}