Search code examples
swiftswift3nsattributedstring

Use of unresolved identifier error in an extension file?


I am making an extension for converting html to an attributed string, the code is

extension String {
var htmlToAttributedString: NSAttributedString? {
    guard let data = data(using: .utf8) else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return htmlToAttributedString?.string ?? ""
}

I am getting the following 3 same errors

Use of unresolved identifier 'NSDocumentTypeDocumentAttribute'

Use of unresolved identifier 'NSHTMLTextDocumentType'

Use of unresolved identifier 'NSCharacterEncodingDocumentAttribute'

i assume i have made a mistake with the syntax to cause 3 of the same error but i couldnt see what else the extension would need?

Thanks


Solution

  • NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute, NSHTMLTextDocumentType and other keys and values for document attribute dictionaries are defined in the AppKit framework (macOS) or in the UIKit framework (iOS):

    #if os(macOS)
        import AppKit
    #elseif os(iOS)
        import UIKit
    #endif