Search code examples
macoswkwebview

Loading a URL with a WKWebView in macOS


I've made a fresh mac app project with the following code in the ViewController.

import Cocoa
import WebKit

class ViewController: NSViewController {

    var loginWebView: WKWebView!
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.loginWebView = WKWebView(frame: self.view.frame)
        
        self.view.addSubview(loginWebView)
        
        let urlReq = URLRequest(url: URL(string: "https://apple.com/")!)
        
        self.loginWebView.load(urlReq)
    }
}

For some reason when I launch the app the web view isn't loading the website. Why is this? I've been developing on iOS for years and am just getting started with macOS.

EDIT: Update loading a local file wouldn't work either

self.loginWebView.loadFileURL(fileURL, allowingReadAccessTo: dirURL)

Solution

  • The problem was that I had not enabled Incoming and Outgoing Connections in my app's sandboxing settings. I discovered this by reverting to using the legacy WebView and then getting an error code in the console. WKWebKit will not print error messages making something really simple incredibly difficult and confusing!. Apple really needs to fix that