Reading HTML String using SwiftUI

Viewed 1591

I'm trying to read HTML formatted content using SwiftUI, I tried using several different methods to load the HTML string but the string was not displayed. I'm using XCode 11.2.1, I will appreciate your help.

import SwiftUI
import Combine
import WebKit

struct SubChapterDetails: View {
    let sentDescription: String
    let webView = WKWebView()

    var body: some View {
           VStack {
               Text("Testing HTML Content")
               Spacer()
               HTMLStringView(htmlContent: "<h1>This is HTML String</h1>")  //It doesn't displays this when the code is executed
               Spacer()
           }
       }
}

struct SubChapterDetails_Previews: PreviewProvider {
    static var previews: some View {
        SubChapterDetails(sentDescription: "")
    }
}

struct HTMLStringView: UIViewRepresentable {
    let htmlContent: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }
}
1 Answers

While having the same issue for a macOS targeted app, I stumbled over this problem as well. Just seconds before I was ready to pull my hair off, I found a mention of entitlements while researching.

So, I went and activated the Outgoing Connections (Client) entitlement – et voilà: it works.

I am quite surprised that this is necessary as the html I want to load is purely local, even in code in my proof of concept right now.

enter image description here

And here's the code:

struct ContentView: View {    

    var body: some View {
        WebViewWrapper(html: "<h1>Hello World!</h1>")
    }
}

struct WebViewWrapper: NSViewRepresentable {
    
    let html: String
    
    func makeNSView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateNSView(_ nsView: WKWebView, context: Context) {
        nsView.loadHTMLString(html, baseURL: nil)
    }
}
Related