swift 3 中的 NSAttributedString 扩展

NSAttributedString extension in swift 3

我正在将我的代码迁移到 swift 3,但我很难使用在以前的 swift 版本上工作的这个扩展。

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}

现在,当我尝试调用这段代码时,出现了这样的异常错误

error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated

这就是我从视图控制器调用方法的方式

let htmlCode = "<html><head><style type=\"text/css\">@font-face {font-family: Avenir-Roman}body {font-family: Avenir-Roman;font-size:15;margin: 0;padding: 0}</style></head><body bgcolor=\"#FBFBFB\">" + htmlBodyCode + "</body>"
newsDescription.attributedText = htmlCode.utf8Data?.attributedString

试试这个:

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}

the official reference 中所述,键 NSCharacterEncodingDocumentAttribute 的值需要是 NSNumber

NSCharacterEncodingDocumentAttribute

The value of this attribute is an NSNumber object containing integer specifying NSStringEncoding for the file;

在较旧的 Swift 中,NSStringEncoding 常量作为 UInt 导入,因此在转换为 AnyObject 时它们会自动桥接到 NSNumber,包含在 NSDictionary.

但是现在,Swift 引入了一个新的枚举类型 String.Encoding,它不是起源于 Objective-C 枚举。不幸的是,现在任何 Swift 类型都可以包含在具有中间隐藏引用类型 _SwiftValueNSDictionary 中,这绝对不是 NSNumber.

因此,您需要传递一些可以桥接到 NSNumber 的内容作为键 NSCharacterEncodingDocumentAttribute 的值。在你的情况下,rawValue 会起作用。

在我看来,这应该得到改进,最好将错误报告发送到 Apple or swift.org

如果有人在 Swift 5.2+ 需要帮助:

extension Data {
    var attributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
        return nil
    }
}