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

To detect when a UIWebView has finished loading in Swift, you can use the UIWebViewDelegate protocol. This protocol provides a set of methods that allow you to receive notifications when various events occur in the web view, including when it finishes loading.

To implement the UIWebViewDelegate protocol, you first need to set the delegate property of your UIWebView instance to an object that conforms to the protocol. This is typically done in your view controller’s viewDidLoad() method, like this:

class ViewController: UIViewController, UIWebViewDelegate {
    
    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.delegate = self
        
        // Load your URL here
        let url = URL(string: "https://www.example.com")
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
    
    // Implement UIWebViewDelegate methods here
    
}

Once you’ve set the delegate property, you can implement the webViewDidFinishLoad() method to receive a notification when the web view has finished loading. This method is called by the UIWebView instance when it finishes loading a web page.

func webViewDidFinishLoad(_ webView: UIWebView) {
    // Web view has finished loading
    print("Finished loading")
}

You can also implement the webView(_:didFailLoadWithError:) method to receive a notification if the web view fails to load the requested page.

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    // Web view failed to load
    print("Failed to load: \(error.localizedDescription)")
}

By using the UIWebViewDelegate protocol, you can easily detect when a UIWebView has finished loading in Swift and take appropriate actions in response to this event.

A pat on the back !!