gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:17:20 40 4
gpt4 key购买 nike

使用 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 + 16 1 WebKitLegacy 0x19242a25c -[_WebSafeForwarder forwardInvocation:] + 132 2 CoreFoundation 0x18c8ea078 forwarding + 404 3 CoreFoundation 0x18c7e459c _CF_forwarding_prep_0 + 92 4 CoreFoundation 0x18c8ec160 invoking_ + 144 5 CoreFoundation 0x18c7dfc3c -[NSInvocation invoke] + 284 6 WebCore 0x19139ac78 HandleDelegateSource(void*) + 108 7 CoreFoundation 0x18c894278 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 24 8 CoreFoundation 0x18c893bc0 __CFRunLoopDoSources0 + 524 9 CoreFoundation 0x18c8917c0 __CFRunLoopRun + 804 10 CoreFoundation 0x18c7c0048 CFRunLoopRunSpecific + 444 11 UIFoundation 0x1926e919c -[NSHTMLReader _loadUsingWebKit] + 1860 12 UIFoundation 0x1926ea424 -[NSHTMLReader attributedString] + 28 13 UIFoundation 0x192689cb4 _NSReadAttributedStringFromURLOrData + 4688 14 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)

关于swift - 使用 NSAttributedString 解码 html 数据时出现奇怪的崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42247736/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com