swift4 - swift4 迁移后 DocumentReadingOptionKey 键损坏

标签 swift4 xcode9

使用以下代码从 swift3 迁移到 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+没有问题,运行iOS 8.3时,控制台输出:"dyld: Symbol not found: _NSCharacterEncodingDocumentOption";它将在注释“.characterEncoding: String.Encoding.utf8.rawValue”后传递。

最佳答案

我找到了解决方案。您应该为 swift4 删除 .characterEncoding。
它适用于 ios8,9,11。

例子:

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
        }
    }

祝你有美好的一天!

关于swift4 - swift4 迁移后 DocumentReadingOptionKey 键损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484650/

相关文章:

ios - XCode 9 在项目之间切换

swift - "Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions"

ios - 将动画添加到以编程方式创建的 UIview

swift - 当我不知道类型时,如何使用类继承进行解码?

swift - 使用UIGestureRecognizer获取UIview的UIabel文字

swift - Xcode 中的 "' deinitialize() ' is deprecated: the default argument to deinitialize(count:) has been removed"警告

ios - 如何访问孙子元素?

ios - 闭包元组不支持 Xcode 9 Swift 4 中的解构

swift - 如何从 Annotation Callout Xcode 9 设置警报

encryption - 如果我使用第三方库进行 AES 加密,App Store 是否接受我的应用程序?