【发布时间】:2017-02-11 22:39:03
【问题描述】:
我正在尝试将一些 html 文本加载到 NSAttributedString 中,但我看到 UI 挂起。
环顾四周,我不确定这是否可能,因为它看起来可能必须在主线程上运行:NSAttributedString from HTML in the background thread
在 swift 3 iOS 10 中,我可以毫无例外地运行它
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)
}
}
几件事。
不知道为什么它不会崩溃。但我怀疑它仍在主线程上运行,因为 UI 仍会锁定几秒钟。
html 中有图片。想知道这是否是造成大部分延误的原因。我仍然想显示图像,但想知道是否可以将它们拉出并最初显示文本并将图像加载到后台线程上。不确定 NSAttributedString 中是否内置了任何东西来提取图像,或者我必须手动解析它们。
有什么办法可以让这些数据加载到后台线程上,这样我就不能在使用用 html 数据初始化的 NSAttributedString 时锁定 UI?
【问题讨论】:
-
你找到解决方案了吗?
标签: html swift grand-central-dispatch nsattributedstring