参见英文答案 >
Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift2个
如何解码我的html字符串:
如何解码我的html字符串:
<span>Bjö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örn is <em>great</em> name" label.attributedText = string.htmlAttributedString()
这将Bj& ouml; rn转换为Björn并将< em> …< / em>斜体化为斜体.部分也是.
如果您只想转换HTML符号并删除HTML标记(例如< span> /< / span>),只需抓住字符串:
let string = "Björn is <em> great </em> name" if let result = string.htmlAttributedString()?.string { print(result) // "Björn is great name" }
对于之前的Swift版本,请参阅此答案的previous revision.