How to create an AttributedString from HTML fragment with an image

36 Views Asked by At

Trying to load an HTML code that contains an image. Tried with:

import SwiftUI

struct ContentView: View {
    @State private var attributed: AttributedString? = ""
    var body: some View {
        VStack {
           
            Text(attributed!)
        }
        .padding()
        .border(Color.purple, width: 4)
        .task{
            
            attributed = loadHTML()!
        }
    }
    
    func loadHTML() -> AttributedString? {
        
        let html = 
"""
<!DOCTYPE html>
<html>
<body>
    <h1>Hello</h1>
    <p>Stack Overflow</p>
    <p><img src="https://static.wixstatic.com/media/198d86_cfc4cc2bc7fa4f13a077c4b7ae3df79a~mv2.png"
        width="200" height="300"></p>
</body>
</html>
"""
        let data =  html.data(using: .utf8)!
      
         guard let nsAttributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
          return nil
        }
        return  try? AttributedString(nsAttributedString, including: \.uiKit)
        
    }
}

#Preview {
    ContentView()
}

But it displays the text without the image. It is not possible to add images to the AttributeString from an HTML fragment?

without image

0

There are 0 best solutions below