Search code examples
swiftswift3uiwebviewwebkit

Check if UIWebView is done loading in Swift


I am making an application that loads a UIWeb View and runs a line of code the moment the webpage is completely loaded.

I am using code like this to load the webpage:

    let links = URL (string: "https://example.com")
    let loadpage = URLRequest(url: links!)
    webPage.loadRequest(load)

How can I run a piece of code the moment the webpage is done? I have tried some examples online but the webpage stops loading while checking if it has loaded?

Thanks!


Solution

  • As stated in the documentation of UIWebView, for apps targeting iOS8 or later you should be using WKWebView instead.

    When using a WKWebView, you can make your class conform to WKNavigationDelegate and the delegate method func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) will be called once the webview finishes loading a network request.

    If for some reason you are still targeting iOS7 or any previous iOS versions and hence the use of a UIWebView, you can use UIWebViewDelegate's func webViewDidFinishLoad(_ webView: UIWebView) method instead.

    Skeleton code for the UIWebView solution:

    class WebVC: UIViewController {
        @IBOutlet weak var webView: UIWebView!
    
        override func viewDidLoad() {
            webView.delegate = self
            let url = URL(string: "https://example.com")
            let request = URLRequest(url: url)
            webView.loadRequest(request)
        }
    }
    
    extension WebVC: UIWebViewDelegate {
        func webViewDidFinishLoad(_ webView: UIWebView) {
            print("Finished loading")
        }
    }