How to show an HTML string on a UILabel in iOS? How to show an HTML string on a UILabel in iOS? ios ios

How to show an HTML string on a UILabel in iOS?


For iOS7 or more you can use this:

NSString * htmlString = @"<html><body> Some html string </body></html>";NSAttributedString * attrStr =   [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding]                                    options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}                        documentAttributes:nil error:nil];UILabel * myLabel = [[UILabel alloc] init];myLabel.attributedText = attrStr;


Swift 2

let htmlText = "<p>etc</p>"if let htmlData = htmlText.dataUsingEncoding(NSUnicodeStringEncoding) {    do {        someLabel.attributedText = try NSAttributedString(data: htmlData,            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],            documentAttributes: nil)    } catch let e as NSError {        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")    }}

Swift 3

let htmlText = "<p>etc</p>"if let htmlData = htmlText.data(using: String.Encoding.unicode) {    do {        let attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)    } catch let e as NSError {        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")    }}


Swift 4+

For Swift 4 and above use:

guard let data = "foo".data(using: String.Encoding.unicode) else { return }try? titleLabel.attributedText =    NSAttributedString(data: data,                   options: [.documentType:NSAttributedString.DocumentType.html],         documentAttributes: nil)