Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying HTML content in UITextView

Tags:

ios

swift

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.

like image 479
Shehroz Saleem Avatar asked Jan 03 '23 00:01

Shehroz Saleem


2 Answers

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
like image 63
Kuldeep Avatar answered Jan 05 '23 14:01

Kuldeep


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)
}
like image 22
kamwysoc Avatar answered Jan 05 '23 16:01

kamwysoc