从HTML创建NSAttributedString必须在主线程上完成!
更新:事实证明,NSAttributedString HTML呈现依赖于WebKit,必须在主线程上运行, 否则偶尔会使用SIGTRAP使应用程序崩溃。
新Relic崩溃日志:
下面是一个更新的线程安全的 Swift 2 String扩展:extension String {
func attributedStringFromHTML(completionBlock:NSAttributedString? ->()) {
guard let data = dataUsingEncoding(NSUTF8StringEncoding) else {
print("Unable to decode data from html string: \(self)")
return completionBlock(nil)
}
let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSNumber(unsignedInteger:NSUTF8StringEncoding)]
dispatch_async(dispatch_get_main_queue()) {
if let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
completionBlock(attributedString)
} else {
print("Unable to create attributed string from html string: \(self)")
completionBlock(nil)
}
}
}}
用法:let html = "
self.bodyLabel.attributedText = attString}