How do I make webview load a specific url when it's opened?

Alright, first off, I am very new to swift, and, it seems complicated. I am trying to code an app for Mac. I only want a webview displayed that loads a specific website when opened. It's for my own personal use. I would really appreciate some guidance. Thanks in advance!

Accepted Reply

The easiest way is to just set mainFrameURL like this:


webView.mainFrameURL = "https://developer.apple.com"


If you want more control over the request, the above is shorthand for


    guard let url = URL(string: "https://developer.apple.com") else { return }
    let request = URLRequest(url: url)
    webView.mainFrame.load(request)


This, of course is supposing that you already created your web view, which you can do either programmatically, like this:


let webView = WebView(frame: NSRect(x: 0, y: 0, width: 400, height: 400))


or just create it by dragging and dropping it into your interface.

Replies

The easiest way is to just set mainFrameURL like this:


webView.mainFrameURL = "https://developer.apple.com"


If you want more control over the request, the above is shorthand for


    guard let url = URL(string: "https://developer.apple.com") else { return }
    let request = URLRequest(url: url)
    webView.mainFrame.load(request)


This, of course is supposing that you already created your web view, which you can do either programmatically, like this:


let webView = WebView(frame: NSRect(x: 0, y: 0, width: 400, height: 400))


or just create it by dragging and dropping it into your interface.

I only want a webview displayed that loads a specific website when opened.

If you’re just starting out I encourage you to use WKWebView rather than WebView; it’s the future!

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"