使用以下代码从 swift3迁移到 swift4, let options: [NSAttributedString.DocumentReadingOptionKey: AnyHashable] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue] let str = try N
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 } }
祝你有美好的一天!