To detect when a WKWebView has finished loading in Swift, you can use the WKNavigationDelegate
protocol. Here are the steps:
- Set the
navigationDelegate
of yourWKWebView
instance to your view controller.
webView.navigationDelegate = self
- Implement the
webView(_:didFinish:)
method of theWKNavigationDelegate
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.