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