MicrorFrank
MicrorFrank

Reputation: 156

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?

Upvotes: 0

Views: 4496

Answers (3)

Joshua Cleetus
Joshua Cleetus

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

Leo Dabus
Leo Dabus

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

Related Questions