Lawrence Gimenez

SwiftUI Journey Part 8: Using WebView in macOS

There is no WebView in SwiftUI, so you have to use the NSViewRepresentable class.


import SwiftUI
import WebKit

struct OnlineJobsWebView: NSViewRepresentable {
    
    var url: URL
    
    func makeNSView(context: Context) -> WKWebView {
        return WKWebView()
    }
    
    func updateNSView(_ webView: WKWebView, context: Context) {
        webView.load(URLRequest(url: url))
    }
}

And you call it in your SwiftUI View.


import SwiftUI

struct AccountView: View {
    var body: some View {
        OnlineJobsWebView(url: URL(string: "https://google.com")!)
    }
}

struct AccountView_Previews: PreviewProvider {
    static var previews: some View {
        AccountView()
    }
}