使用NSAttributedString解码html数据时出现奇怪的崩溃



使用NSAttributedString解码html数据时出现奇怪的崩溃,请查看下面的函数和崩溃日志。当试图解码一个奇怪的崩溃发生

func decodeHTML() -> String {
var attributedString = NSAttributedString(string :self)
let encodedData = self.data(using: String.Encoding.utf8)!
let attributedOptions : [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
//webkitlegacy crash. It should run in main thread
if Thread.isMainThread {
do {
attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
} catch {
print("Unexpected error occured inside decodeHTML")
}
} else {
DispatchQueue.main.sync {
do {
attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
} catch {
print("Unexpected error occured inside decodeHTML")
}
}
}
return attributedString.string
}
}    
I got below crash logs , please let me know how to avoid such crash

获取以下日志:

0 libobjc。A.dylib 0x18b332f30 objc_msgSend+161 WebKitLegacy 0x19242a25c-[_WebSafeForwarder转发调用:]+1322 CoreFoundation 0x18c8ea078转发+4043核心基础0x18c7e459c _CF_forwarding_prep_0+924核心基础0x18c8ec160调用_+1445 CoreFoundation 0x18c7dfc3c-[NSI位置调用]+2846 WebCore 0x19139ac78 HandleDelegateSource(void*)+1087核心基础0x18c894278CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION+248核心基础0x18c893bc0 __CFRunLoopDoSources0+5249核心基础0x18c8917c0 __CFRunLoopRun+80410 CoreFoundation 0x18c7c0048 CFRunLoopRunSpecific+44411 UIFoundation 0x1926e919c-[NSHTMLReader_loadUsingWebKit]+186012 UIFoundation 0x1926ea424-[NSHTMLReader属性字符串]+2813 UIFoundation 0x192689cb4 _NSReadAttributedStringFromURLData+468814 UIFoundation 0x1926889bc-[

试试这个-

extension String {
init(htmlEncodedString: String) {
self.init()
guard let encodedData = htmlEncodedString.data(using: .utf8) else {
self = htmlEncodedString
return
}

do {
let attributedString = try NSAttributedString(data: encodedData, options: [.documentType: NSAttributedString.DocumentType.html] , documentAttributes: nil)
self = attributedString.string
} catch {
print("Error: (error)")
self = htmlEncodedString
}
}
}

调用上面类似下面的方法-

let html = "<center>Here is some <b>HTML</b></center>"
let decodedString = String(htmlEncodedString: html)
print(decodedString)

最新更新