How to detect when a WKWebView has finished loading in Swift?

To detect when a WKWebView has finished loading in Swift, you can use the WKNavigationDelegate protocol. Here are the steps:

  1. Set the navigationDelegate of your WKWebView instance to your view controller.
webView.navigationDelegate = self
  1. Implement the webView(_:didFinish:) method of the WKNavigationDelegate protocol. This method is called when the web view finishes loading its content.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    // Web view finished loading content
}

Here’s the complete code for loading a URL in a WKWebView and detecting when it has finished loading:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set the navigation delegate
        webView.navigationDelegate = self

        // Load a URL in the web view
        if let url = URL(string: "https://www.example.com") {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // Web view finished loading content
        print("Web view finished loading")
    }
}

You can customize the code to perform different actions when the web view finishes loading.

A pat on the back !!