Swift - 将 HTML 文本转换为属性字符串

Swift - Convert HTML text to Attributed String

在我的一个模块中,我想使用 UILabel 将多语言 HTML 文本(英语和泰米尔语)显示为 NSAttributedString。如果文本是纯英文的,我可以按我的意愿显示。但是我的内容包含英语和泰米尔语字符。我该如何处理这种情况。请分享您的建议,如果有人知道的话。

HTML Content

<medium><b><font color='#2f3744'>IPL Tamil Web Series Episode #3 | யாருடா Swetha ? | Tamil Comedy Web Series | Being Thamizhan</font></b></medium> has been succesfully scheduled on <medium><b><font color='#2f3744'>2018-05-23 08:51 PM</font></b></medium>

Expectation

IPL 泰米尔语网络系列第 3 集 | யாருடாSwetha? |泰米尔喜剧网络系列 |成为 Thamizhan 已成功安排在 2018-05-23 08:45 PM

Current Output

IPL 泰米尔语网络系列第 3 集 | &*$%!@#$@^&$&^%$ Swetha? |泰米尔喜剧网络系列 |成为 Thamizhan 已成功安排在 2018-05-23 08:45 PM

注意:我尝试使用下面的代码片段来存档这个

extension String {
var htmlToAttributedString: NSAttributedString? {
    guard let data = data(using: .utf8) else { return NSAttributedString() }
    do {
        return try NSAttributedString(data: data, options:
            [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
    } catch {
        return NSAttributedString()
    }
}
var htmlToString: String {
    return htmlToAttributedString?.string ?? ""
}
}

我用你的 html 试过这个解决方案,效果很好:

let htmlText = "<medium><b><font color='#2f3744'>IPL Tamil Web Series Episode #3 | யாருடா Swetha ? | Tamil Comedy Web Series | Being Thamizhan</font></b></medium> has been succesfully scheduled on <medium><b><font color='#2f3744'>2018-05-23 08:51 PM</font></b></medium>"
let encodedData = htmlText.data(using: String.Encoding.utf8)!
var attributedString: NSAttributedString

do {
    attributedString = try NSAttributedString(data: encodedData, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)
} catch let error as NSError {
    print(error.localizedDescription)
} catch {
    print("error")
}

attributedString 输出:

IPL 泰米尔语网络系列第 3 集 | யாருடாSwetha? |泰米尔喜剧网络系列 |成为 Thamizhan 已成功安排在 2018-05-23 08:45 PM