5

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)
    }
}
3
  • Your HTMLStringView is shown perfectly on my machine using XCode 11.3.1 Commented Mar 14, 2020 at 13:11
  • @Mamaessen for me, I'm having this error/warning on my debug console what could i be missing? >> Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service Commented Mar 14, 2020 at 13:16
  • Code is working for me via Xcode 12.3 beta. Commented Nov 20, 2020 at 0:21

1 Answer 1

8

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)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any comparable solution for iOS apps?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.