NSAttributedString 在初始化时崩溃,但为什么呢?

Jea*_*ler 5 encoding nsattributedstring swift

有时这件事会崩溃,但我不知道为什么以及何时崩溃。有人有想法吗?

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
}
}
Run Code Online (Sandbox Code Playgroud)

这是我从 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)
Run Code Online (Sandbox Code Playgroud)

Fan*_*ing 1

我强烈建议您升级到 swift 4。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
    }
}
Run Code Online (Sandbox Code Playgroud)