Swift 3 - Check if WKWebView has loaded page

Viewed 46501

My question: How do I check if a page in WKWebView has fully loaded in Xcode using Swift 3?

This is my problem:

Webpage 1: From this page I load Webpage 2

Webpage 2: I need to get html data from Webpage 2, but when I print the HTML data I get HTML data of webpage 1, which I don't want. But when I print HTML data 2 seconds later it gives me the right HTML data.

I need to know whether or not a page in WKWebView did finish loading. I can see in the WebView it is loaded and also the progressbar is fully loaded, but when I print html data of the page I get html data of previous page, which is not what I want. Only if I wait a second it gives the right data, probably cause Webpage 2 is loaded.

So how do I let Xcode to print html when the next page is totally loaded?

I have tried several methods:

Maybe I can use:

if webView.isloading { get } but I don't know how to implement this method and if it should work. I have tried several methods from Stack but these are not working for me or outdated.

Do you guys know a solution for this problem in Swift 3? Thanks!

2 Answers

Set delegate > WKNavigationDelegate

Objective-C

// Start loading WKWebView
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"Start loading");
} 

//Finished loading WKWebView
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"End loading");
}

Swift 4.2

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    print("Start loading")    
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("End loading")
}
Related