4

Using the following code migrated from swift3 to swift4,

let options: [NSAttributedString.DocumentReadingOptionKey: AnyHashable] =
                          [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue]

            let str = try NSAttributedString( data:string!.data(using: String.Encoding.utf8, allowLossyConversion: true
                )!, options:options, documentAttributes: nil)

iOS 9+ has no problem, when running iOS 8.3, console output: "dyld: Symbol not found: _NSCharacterEncodingDocumentOption"; It would be passed after commented ".characterEncoding: String.Encoding.utf8.rawValue".

Jenus Dong
  • 304
  • 2
  • 7

2 Answers2

4

I found the solution. You should to remove .characterEncoding for swift4. It works on ios8,9,11.

Example:

public func htmlToString() -> String? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(
                data: data,
                options: [
                    .documentType: NSAttributedString.DocumentType.html
                ],
                documentAttributes: nil
            ).string
        } catch let error as NSError {
            print(error.localizedDescription)
            return  nil
        }
    }

Have a good day!

nullproduction
  • 576
  • 3
  • 18
  • Thanks @nullrpoduction. It doesn‘t work on iOS 10? YES, remove .characterEncoding can works. Course default encoding is UTF-8, so it works. But if not encoded utf-8, how to do? – Jenus Dong Oct 09 '17 at 01:30
  • For example, my project using the following code [unicode encoding]: try NSAttributedString( data: string.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options:[.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil ) – Jenus Dong Oct 09 '17 at 01:36
  • Thanks, my app was working fine above iOS 8 and for iOS 8, the problem turned out to be what you said. Saved me a lot. – kubilay Oct 31 '17 at 04:43
  • 1
    @kubilay For iOS 8, use this way would work `NSAttributedString.DocumentReadingOptionKey(rawValue: "CharacterEncoding")` – Terence May 18 '18 at 20:47
1

For all iOS 8, use this way for the key

NSAttributedString.DocumentReadingOptionKey(rawValue: "CharacterEncoding")

instead of putting

NSAttributedString.DocumentReadingOptionKey.characterEncoding

directly.

Note: Don't use version check to call NSAttributedString.DocumentReadingOptionKey.characterEncoding, otherwise, it still doesn't work.

Terence
  • 443
  • 3
  • 13