WKWebView doesn't show on Playground

Viewed 281

When I run the code below on Xcode 11.5 Playground, the Text view shows, but not the custom view WebView. I don't get any errors too.

import SwiftUI
import PlaygroundSupport
import WebKit

struct webView: View {
    var body: some View {
        VStack {
            Text("Test")
            WebView(request: URLRequest(url: URL(string: "http://www.google.com")!))
        }
    }
}
PlaygroundPage.current.setLiveView(webView())

struct WebView : NSViewRepresentable {
    
    var request: URLRequest
    
    func makeNSView(context: Context) -> WKWebView  {
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true

        let config = WKWebViewConfiguration()
        config.preferences = preferences
        let webView = WKWebView(frame: .zero, configuration: config)
        webView.frame = NSRect(x: 0, y: 0, width: 400, height: 300)
        DispatchQueue.main.async {
            webView.load(self.request)
        }
        return webView
    }
    
    func updateNSView(_ nsView: WKWebView, context: Context) {
    }
    
}

The same code works in the main code, but not on Playground. I'm not sure what's wrong.

1 Answers

You need to specify frame explicitly (as there is no window)

PlaygroundPage.current.setLiveView(webView().frame(width: 400, height: 300))
Related