Reputation: 156
I am trying to display an HTML string in UITextView. Here is the key line:
self.postPage.attributedText = NSAttributedString(string: myHTMLString)
The problem I saw is that the <div>
tags <img>
tags are still showing... is there anything I am doing wrong?
Upvotes: 0
Views: 4496
Reputation: 672
This function will convert all the HTML tags into NSAttributedString
.
extension String{
func convertHtml() -> 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()
}
}
}
Usage is like:
yourTextView.attributedText = yourHtmlString.convertHtml()
Upvotes: 0
Reputation: 990
Need to add try!
if you use Xcode 7.0.1.
extension String {
var html2String:String {
return try! NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil).string
}
}
Upvotes: 3
Reputation: 236568
extension String {
var html2String:String {
return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil, error: nil)!.string
}
}
"<div>Testing<br></div><img src=\"http://....\">".html2String // "Testing\n"
Upvotes: 3