how do I get WKWebView to work in swift and for an macOS App

i0S Swift Issue

Question or problem in the Swift programming language:

before this get’s shot down for being a duplicate, it isn’t. Pretty much every question on WKWebView here is about WKWebView in iOS Apps, not macOS Apps, with the difference being pretty much just the UIViewController interface being implemented instead of the NSViewController interface in macOS.

The example code in Apple’s Documentation as well as the Controller code, that can be found online doesn’t work. Altough it does compile without a problem the webview stays inactive.

Is there something that I just didn’t see or is this a bug in WKWebView ?
I even copied some code from tutorials showing how to do this for iOS and just changed UIViewController to NSViewController (since that was the ONLY difference), yet it didn’t work.

The following code in ViewController.swift does not work.
It also doesn’t work if it’s
class ViewController: NSViewController, WKUIDelegate

import Cocoa;
import WebKit;
class ViewController: NSViewController {
    @IBOutlet weak var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let url=URL(string: "http://safetec-cam.biz/images/webcam_extern/bad-nauheim_bahnhof_west.jpg");
        webView.load(URLRequest(url: url!));
    }
}

it also doesn’t work if it’s done like this with the UIViewController exchanged for NSViewController
image from https://developer.apple.com/documentation/webkit/wkwebview

How to solve the problem:

I recommend you to start from scratch:

Set Your URL to be loaded:

let myURLString = "https:yourWebLink"
let url = URL(string: myURLString)
let request = URLRequest(url: url!)

Init and load request in webview:

let webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.load(request)

Implement WKNavigationDelegate to trace your page Load/Error:

extension ViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Started to load")
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Finished loading")
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(error.localizedDescription)
    }
}

For further reference check: https://iosdevcenters.blogspot.com/2016/05/creating-simple-browser-with-wkwebview.html