WKView content doesn't display in NSViewRepresentable

Viewed 511

I ran into an issue when I put WKWebView in NSViewRepresentable then my app shows a black screen instead of the loaded web page.

import SwiftUI
import WebKit

struct TestView : NSViewRepresentable {
    func makeNSView(context: Context) -> WKWebView  {
        let view = WKWebView()
        if let url = URL(string: "https://www.google.com/") {
            view.load(URLRequest(url: url))
        }
        return view
    }

    func updateNSView(_ view: WKWebView, context: Context) {
    }

}


struct ContentView: View {
    var body: some View {
        TestView()
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

enter image description here

1 Answers

One thing not to oversee on macOS is to turn on "Outgoing Connections" in App Sandbox options.

enter image description here

Of course "Allow Arbitrary Loads" may be on yes as well.

enter image description here

If you want to go one step further you should consider to implement a Coordinator as mentioned from LuLuGaGa.

Related