栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Swift中解码HTML实体?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Swift中解码HTML实体?

这个答案最近针对Swift 5.2和iOS 13.4 SDK进行了修订。


没有做到这一点的直接方法,但是您可以使用

NSAttributedString
魔术使此过程尽可能轻松(请注意,此方法也将剥离所有HTML标记)。

记住 仅从主线程 初始化

NSAttributedString
。它使用WebKit解析下面的HTML,因此是必需的。

// This is a[0]["title"] in your caselet enpredString = "The Weeknd <em>&#8216;King Of The Fall&#8217;</em>"guard let data = htmlEnpredString.data(using: .utf8) else {    return}let options: [NSAttributedString.documentReadingOptionKey: Any] = [    .documentType: NSAttributedString.documentType.html,    .characterEncoding: String.Encoding.utf8.rawValue]guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {    return}// The Weeknd ‘King Of The Fall’let depredString = attributedString.stringextension String {    init?(htmlEnpredString: String) {        guard let data = htmlEnpredString.data(using: .utf8) else { return nil        }        let options: [NSAttributedString.documentReadingOptionKey: Any] = [ .documentType: NSAttributedString.documentType.html, .characterEncoding: String.Encoding.utf8.rawValue        ]        guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else { return nil        }        self.init(attributedString.string)    }}let enpredString = "The Weeknd <em>&#8216;King Of The Fall&#8217;</em>"let depredString = String(htmlEnpredString: enpredString)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/436427.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号