DocumentReadingOptionKey key corrupt after swift4 migration

Viewed 809

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".

2 Answers

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!

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.

Related