有时候这东西会崩溃,但我不知道为什么和何时。 有人有主意吗?
extension String {
var htmlDecoded: String? {
if let encodedData = self.data(using: String.Encoding.utf8) as Data? {
let attributedOptions = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
do {
let attributedString = try NSAttributedString(data: encodedData,
options: attributedOptions,
documentAttributes: nil)
return attributedString.string
} catch let error as NSError {
print("ERROR: ", error.localizedDescription)
return self
}
}
return self
}
}
这是我从HockeyApp得到的错误
function signature specialization <Arg[0] = Owned To Guaranteed and Exploded> of @nonobjc (extension in UIKit):__C.NSAttributedString.init(data: Foundation.Data, options: [Swift.String : Any], documentAttributes: Swift.AutoreleasingUnsafeMutablePointer<__C.NSDictionary?>?) throws -> __C.NSAttributedString (String+html.swift:0)
function signature specialization <Arg[0] = Exploded> of (extension in Podcat_2):Swift.String.htmlDecoded.getter : Swift.String? (String+html.swift:0)
答案 0 :(得分:0)
我强烈建议您升级到swift4。在swift 4中对字体进行了很多更改,最好尽早进行更改。
这是我的Swift 4版本,非常适合将html字符串转换为NSAttributedString
。然后,您可以调用.string
来获取字符串本身。
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
return html
}
}