Search code examples
webkitxcode9

Xcode 9.2 - WebView doesn't work


I'm trying to build a simple webView application for MacOS, but it doesn't seem to work. I've linked the code to the storyboard, imported WebKit, but nothing seems to work. After I finish the build, and try to test it, the window keeps gray. There are no errors involved. Does anyone know what I did wrong?

CODE:

import Cocoa
import WebKit

class ViewController: NSViewController {

    @IBOutlet var webView: WebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView.mainFrame.load(URLRequest(url: URL(string: "http://apple.com")!))

    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

Solution

  • You should be using a WKWebView instead of a WebView. WKWebView replaced WebView in macOS 10.10.

    @IBOutlet var webView: WKWebView?
    

    To load a webpage create a URL request with the webpage's URL. Call the web view's load() function to load the webpage with the URL request. The following code should load Apple's website in a WKWebView:

    override func viewDidLoad() {
        super.viewDidLoad()
        loadWebContent()
    }
    
    func loadWebContent() {
        if let myURL = URL(string: "https://www.apple.com") {
            let myRequest = URLRequest(url: myURL)
            webView?.load(myRequest)
        }
    }
    

    One last thing you have to deal with is the app sandbox. Xcode projects initially have the app sandbox turned on. The app sandbox is set initially to disallow any incoming and outgoing network connections. Either allow incoming and outgoing network connections or turn off the sandbox.

    enter image description here