Swift - Convert HTML text to Attributed String

廉价感情. 提交于 2020-12-04 04:53:30

问题


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 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 Tamil Web Series Episode #3 | யாருடா Swetha ? | Tamil Comedy Web Series | Being Thamizhan has been succesfully scheduled on 2018-05-23 08:45 PM

Current Output

IPL Tamil Web Series Episode #3 | &*$%!@#$@^&$&^%$ Swetha ? | Tamil Comedy Web Series | Being Thamizhan has been succesfully scheduled on 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 ?? ""
}
}

回答1:


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

IPL Tamil Web Series Episode #3 | யாருடா Swetha ? | Tamil Comedy Web Series | Being Thamizhan has been succesfully scheduled on 2018-05-23 08:45 PM



来源:https://stackoverflow.com/questions/50506888/swift-convert-html-text-to-attributed-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!