当前位置 : 主页 > 手机开发 > 其它 >

DocumentReadingOptionKey键在swift4迁移后损坏

来源:互联网 收集:自由互联 发布时间:2021-06-11
使用以下代码从 swift3迁移到 swift4, let options: [NSAttributedString.DocumentReadingOptionKey: AnyHashable] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue] let str = try N
使用以下代码从 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:找不到符号:_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
        }
    }

祝你有美好的一天!

网友评论