Html tags are coming in string from api response, need to display formatted string not with the tags. Below is my code what i tried:
html String:
"<span class="st"><em>Bread<\/em> is a staple food, usually by baking. Throughout ... <em>Sourdough<\/em> is a type of <em>bread<\/em> produced by dough using naturally occurring yeasts and lactobacilli. ... List of <em>toast<\/em> dishes<\/span>",
code tried:
let data = Data(vm.description!.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
infoDescription.attributedText = attributedString
}
Other methods tried:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
Please guide what wrong i am doing or what is missing. Thanks
You need to decode HTML entities first then you can use your current implementation to get your styled string.
For HTML entities decoding you can refer this: https://stackoverflow.com/a/30141700/3867033
But I found that you can use NSAttributesString to achieve the same result.
let html1 = """
<span class="st"><em>Bread</em> is a staple food, usually by baking. Throughout ... <em>Sourdough</em> is a type of <em>bread</em> produced by dough using naturally occurring yeasts and lactobacilli. ... List of <em>toast</em> dishes</span>
"""
extension String {
var toAttributedString: NSAttributedString? {
return try? NSAttributedString(
data: data(using: .utf8)!,
options: [
.documentType: NSAttributedString.DocumentType.html,
],
documentAttributes: nil)
}
}
let output1 = html1.toAttributedString!.string
let output2 = output1.toAttributedString
It's a little bit weird for me too, but it works...