Shehroz Saleem
Shehroz Saleem

Reputation: 196

Displaying HTML content in UITextView

I would like to display the String HTML in a UITextView control using swift. I found some code and tried it:

     do {
        let str = try NSAttributedString(data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
    } catch {
        print(error)
    }

but i gives some error i am unable to understand or found any solution, which states as,

Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey'

I need to figure out why i am having this error. Any solution or alternate code? The other solutions are in objective-c if they either have answers they are giving the same error i tried many just because of old versions.

Upvotes: 4

Views: 9472

Answers (4)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Try this

   let htmlString = "<html><body> Some html string </body></html>";

    do {
        let str = try NSAttributedString(data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)

        self.txView.attributedText  = str

    } catch {
        print(error)
    }

Upvotes: 0

dahiya_boy
dahiya_boy

Reputation: 9503

Use this, it is properly working for me

let attrStr = try! NSAttributedString(
            data: htmlText.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

Upvotes: 0

Kuldeep
Kuldeep

Reputation: 4552

Try This

var attrStr = try! NSAttributedString(
            data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
            options:[NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        YOUR_TEXTVIEW.attributedText = attrStr

Upvotes: 7

kamwysoc
kamwysoc

Reputation: 6859

Change options to

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

So it should be:

 do {
    let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
    let str = try NSAttributedString(data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: options, documentAttributes: nil)
} catch {
    print(error)
}

Upvotes: 2

Related Questions