close

Show HTML in TextView Swift 3

QuestionsCategory: SwiftShow HTML in TextView Swift 3
Adeel asked 2 months ago

I’ve a textview and I’m getting string like

<p>This is a line in a paragraph</p>

I want to display this in a textview but it should convert <p> to what it means for the web. How can I do this?

1 Answers
Chaudhary Talha Staff answered 2 months ago

Make a function:

private func stringFromHtml(string: String) -> NSAttributedString? {
         do {
             let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
             if let d = data {
                 let str = try NSAttributedString(data: d,
                                                  options: [.documentType: NSAttributedString.DocumentType.html,
                                                            .characterEncoding: String.Encoding.utf8.rawValue],
                                                  documentAttributes: nil)
                 return str
             }
         } catch {
             print("error: ", error)
         }
         return nil
     }

and then to give it to text view:

yourTextView.attributedText = stringFromHtml(string: content)