ReadingOptionKey document corrupted after swift4 migration

Using the following code ported 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 problems starting iOS 8.3, console output: "dyld: Symbol not found: _NSCharacterEncodingDocumentOption"; It will be transmitted after commenting ".characterEncoding: String.Encoding.utf8.rawValue".

+4
source share
1 answer

I have found a solution. You must 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 nice day!

+4
source

Source: https://habr.com/ru/post/1686617/


All Articles