NSAttributedString extension in swift 3
Try this:
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
}
}
As described in the official reference, the value for key NSCharacterEncodingDocumentAttribute
needs to be an NSNumber
.
NSCharacterEncodingDocumentAttribute
The value of this attribute is an
NSNumber
object containing integer specifyingNSStringEncoding
for the file;
In older Swifts, NSStringEncoding
constants are imported as UInt
s, so they are automatically bridged to NSNumber
when converted to AnyObject
, as contained in NSDictionary
.
But now, Swift introduced a new enum type String.Encoding
which is not originated as an Objective-C enum. And unfortunately, now any Swift types can be contained in an NSDictionary
with intermediate hidden reference type _SwiftValue
, which definitely is NOT an NSNumber
.
So, you need to pass something which can be bridged to NSNumber
as the value for key NSCharacterEncodingDocumentAttribute
. In your case, rawValue
would work.
In my opinion, this should be improved, and better send a bug report to Apple or swift.org.
In case anyone needs assistance in 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
}
}