解码HTML字符串

参见英文答案 > Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift2个
如何解码我的html字符串:
<span>Bj&ouml;rn</span>

<span>Björn</span>

在Swift 3?

解决方法

你真的需要保留< span>标签,同时替换& ouml;符号? Leo Dabus在 Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift中提出的一种技术转换符号包括通过属性字符串将其往返.

在Swift 4中:

extension String {
    /// Converts HTML string to a `NSAttributedString`

    var htmlAttributedString: NSAttributedString? {
        return try? NSAttributedString(data: Data(utf8),options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue],documentAttributes: nil)
    }
}

如果您想要一个属性字符串(例如,用于UILabel)

let string = "Bj&ouml;rn is <em>great</em> name"
label.attributedText = string.htmlAttributedString()

这将Bj& ouml; rn转换为Björn并将< em> …< / em>斜体化为斜体.部分也是.

如果您只想转换HTML符号并删除HTML标记(例如< span> /< / span>),只需抓住字符串:

let string = "Bj&ouml;rn is <em> great </em> name"
if let result = string.htmlAttributedString()?.string {

    print(result)   // "Björn is great name"
}

对于之前的Swift版本,请参阅此答案的previous revision.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些