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

时间:2018-05-24 10:23:59

标签: html ios swift nsattributedstring

在我的一个模块中,我希望使用UILabel将多语言HTML文本(英语和泰米尔语)显示为NSAttributedString。如果文本是纯英文,我可以将其显示为我的愿望Using this way。但我的内容包含英文和泰米尔语字符。我该怎么处理这个场景。如果有人知道,请分享您的建议。

  

HTML内容

<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>
  

期望

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

  

当前输出

IPL泰米尔语网络系列第3集| &amp; * $%!@#$ @ ^&amp; $&amp; ^%$ 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 ?? ""
}
}

1 个答案:

答案 0 :(得分:8)

我用你的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