Нет простого способа сделать это, но вы можете использовать магию NSAttributedString
, чтобы сделать этот процесс максимально безболезненным (следует предупредить, что этот метод также удалит все теги HTML):
let encodedString = "The Weeknd <em>‘King Of The Fall’</em>"
// encodedString should = a[0]["title"] in your case
guard let data = htmlEncodedString.data(using: .utf8) else {
return nil
}
let options: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
return nil
}
let decodedString = attributedString.string // The Weeknd ‘King Of The Fall’
Не забудьте инициализировать NSAttributedString только из основного потока. Он использует некоторую магию WebKit под этим, поэтому это требование.
Вы можете создать собственное расширение String
для увеличения повторного использования:
extension String {
init?(htmlEncodedString: String) {
guard let data = htmlEncodedString.data(using: .utf8) else {
return nil
}
let options: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
return nil
}
self.init(attributedString.string)
}
}
let encodedString = "The Weeknd <em>‘King Of The Fall’</em>"
let decodedString = String(htmlEncodedString: encodedString)