Swift-将HTML文本转换为属性字符串 [英] Swift - Convert HTML text to Attributed String

查看:51
本文介绍了Swift-将HTML文本转换为属性字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模块之一中,我想使用UILabel将多语言HTML文本(英语和泰米尔语)显示为NSAttributedString.如果文字是纯英文,我可以将其显示为我的愿望

In one of my module, I want show the multiple language HTML texts (English and Tamil) as a NSAttributedString using UILabel. If the text would be pure english, I can show it as my desire Using this way. But my content has contain both English and Tamil characters. How could I handle this scenario. Kindly share your suggestions, If anyone know about that.

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集|யாருடா斯威莎?|泰米尔语喜剧网络系列|已成功预定为Thamizhan ,时间为 2018-05-23 08:45 PM

电流输出

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

注意:我尝试使用下面的代码片段将其存档

Note: I tried with below code snippet to archive this

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尝试了此解决方案,并且运行良好:

I tried this solution with your html and worked fine:

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集|யாருடா斯威莎?|泰米尔语喜剧网络系列|已成功预定为Thamizhan ,时间为 2018-05-23 08:45 PM

这篇关于Swift-将HTML文本转换为属性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆