Convert HTML to Text

In my SwiftUI project, I am trying to convert HTML to Text.

Text("<h1>Test</h1><p >Test</p><br/><span>Test</span><ul><li>item1</li><li>item2</li></ul")
          .font(.body)
          .frame(maxWidth: .infinity, alignment: .leading)
          .padding(.bottom, 16)
         
Is there a way to make it happen ?

Thank you
Answered by ForumsContributor in
Accepted Answer
As for now, there's no support for rendering HTML in SwiftUI.

You may need to wrap WKWebView or UILabel with NSAttributedString into UIViewRepresentable.

You can send a feature request using Apple's Feedback Assistant.

One another option would be converting NSAttributedString to String and you can use SwiftUI Text. (detailStr)

String+Extension

extension String {
    func htmlToString() -> String {
        return  try! NSAttributedString(data: self.data(using: .utf8)!,
                                        options: [.documentType: NSAttributedString.DocumentType.html],
                                        documentAttributes: nil).string
    }
}

SwiftUI

 Text(str.htmlToString())
Convert HTML to Text
 
 
Q