Search code examples
iosswiftuitextviewnsattributedstring

Display HTML string in UITextView


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?


Solution

  • 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"