How to display HTML content in UILabel Swift 3
First we take a HTML string as input and then process this string to generate an Attributed String which can be set to the UILabel. Below are the steps in the process:
- Data is taken from the string using the unicode encoding.
let data = string.data(using: String.Encoding.unicode, allowLossyConversion: true)
- Using the NSHTMLTextDocumentType, an NSAttributedString is generated.
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
- This string can be set to the UILabel to display HTML formatted text.
myLabel.attributedText = str
Have a look at the complete function below:
private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.unicode, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
} catch {
print ("Failed to get HTML from string")
}
return nil
}
This function has been written in Swift 3.