How to load a URL in a WKWebView in Swift?

Loading a URL in a WKWebView in Swift is quite similar to loading it in a UIWebView. Here’s how to do it:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    
    var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create a WKWebView instance
        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        view.addSubview(webView)
        
        // Load the URL
        if let url = URL(string: "https://www.example.com") {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
    
    // WKNavigationDelegate method to handle page loading
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Page loaded")
    }
}

In the above code, we first import the WebKit framework and declare a WKWebView instance as a class variable. Then, in the viewDidLoad method, we create the WKWebView, set its navigationDelegate to self, and add it as a subview to the current view.

Next, we check if the URL we want to load is valid and create a URLRequest instance from it. Finally, we call the load method on the webView instance and pass in the URLRequest.

To handle the completion of page loading, we implement the webView(_:didFinish:) method of the WKNavigationDelegate protocol.

That’s it! The URL will now be loaded in the WKWebView.

A pat on the back !!