解码 HTML 字符串

Decode HTML string

如何从以下位置解码我的 html 字符串:

<span>Bj&ouml;rn</span>

<span>Björn</span>

在 Swift 3 ?

您真的需要保留 <span> 标签,同时替换 &ouml; 符号吗? Leo Dabus 在 中建议的一种技术转换符号包括通过属性字符串来回转换符号。

在 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>),只需抓住 string:

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