swift中的NSAttributedString扩展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 } }
现在,当我尝试调用这段代码时,我得到一个像这样的exception错误
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 } }
正如在官方的参考文献中所描述的 , NSCharacterEncodingDocumentAttribute
关键字的值需要是一个NSNumber
。
NSCharacterEncodingDocumentAttribute
此属性的值是一个
NSNumber
对象,它包含指定文件的NSStringEncoding
整数;
在较老的Swift中, NSStringEncoding
常量被导入为UInt
,所以当它们被转换为AnyObject
,会自动桥接到NSNumber
,如NSDictionary
所包含的那样。
但是现在,Swift引入了一个新的枚举typesString.Encoding
,它不是作为一个Objective-C枚举出现的。 不幸的是,现在任何Swifttypes都可以包含在一个带有中间隐藏引用types_SwiftValue
的NSDictionary
,它绝对不是一个NSNumber
。
所以,你需要传递一些东西,可以桥接到NSNumber
作为关键的NSCharacterEncodingDocumentAttribute
的值。 在你的情况下, rawValue
会工作。
在我看来,这应该有所改进,更好地向苹果或swift.org发送错误报告。
如果有人需要帮助Swift 4+ :
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 } }