Display html text in uitextview
For Swift 4, Swift 4.2: and Swift 5
let htmlString = """
<html>
<head>
<style>
body {
background-color : rgb(230, 230, 230);
font-family : 'Arial';
text-decoration : none;
}
</style>
</head>
<body>
<h1>A title</h1>
<p>A paragraph</p>
<b>bold text</b>
</body>
</html>
"""
let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)
textView.attributedText = attributedString
For Swift 3:
let htmlString = """
<html>
<head>
<style>
body {
background-color : rgb(230, 230, 230);
font-family : 'Arial';
text-decoration : none;
}
</style>
</head>
<body>
<h1>A title</h1>
<p>A paragraph</p>
<b>bold text</b>
</body>
</html>
"""
let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)
let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
textView.attributedText = attributedString
Use following block of code for ios 7+.
NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: nil
];
textView.attributedText = attributedString;