将html转化为字符串

只谈情不闲聊 提交于 2020-08-11 12:38:21

在项目中你遇到一个需要显示html的需求,但直接显示的话,会有显示一些不需要的符号,需做一些处理

个人喜好用扩展

extension String {
    var htmlAttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: Data(utf8),
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            print("error: ", error)
            return nil
        }
    }
    var htmlString: String {
        return htmlAttributedString?.string ?? self
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!