Web view

Posted on March 10, 2020



A WKWebView from the WebKit framework is used to display web content in a window. The web view can be wrapped with NSViewRepresentable to make it usable with SwiftUI. Content for the web view can be loaded using a website url, a string representing HTML content, or by loading an HTML file.

import SwiftUI
import WebKit

// A view representing a WKWebView for displaying a webpage using a url.

struct WebView: NSViewRepresentable {

    let url: String

    func makeNSView(context: Context) -> WKWebView {

        guard let url = URL(string: self.url) else {
            return WKWebView()
        }

        let webview = WKWebView()
        let request = URLRequest(url: url)
        webview.load(request)
        return webview
    }

    func updateNSView(_ nsView: WKWebView, context: Context) { }
}
// A view representing a WKWebView for displaying HTML content.

struct WebView: NSViewRepresentable {

    let content: String

    func makeNSView(context: Context) -> WKWebView {

        let webview = WKWebView()
        webview.loadHTMLString(self.content, baseURL: nil)
        return webview
    }

    func updateNSView(_ nsView: WKWebView, context: Context) { }
}
// A view representing a WKWebView for displaying an HTML file.

struct WebView: NSViewRepresentable {

    let file: String

    func makeNSView(context: Context) -> WKWebView {

        guard let url = Bundle.main.url(forResource: self.file, withExtension: "html") else {
            return WKWebView()
        }

        let webview = WKWebView()
        webview.loadFileURL(url, allowingReadAccessTo: url)
        return webview
    }

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

For SwiftUI to properly display the WebView, it must be within a GeometryReader and ScrollView.

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            GeometryReader { geom in
                ScrollView {
                    WebView(url: "https://www.apple.com")
                        .frame(height: geom.size.height)
                }
            }
            Text("Apple's website")
        }
        .padding()
        .frame(width: 480, height: 600)
    }
}

web view



Back


Gavin Wiggins © 2020