How to detect when a UIWebView has completely finished loading?

╄→尐↘猪︶ㄣ 提交于 2019-11-30 11:18:05

Use the UIWebViewDelegate protocol method webViewDidFinishLoad and webView's isLoading property

 - (void)webViewDidFinishLoad:(UIWebView *)webView
 {
    //Check here if still webview is loding the content
    if (webView.isLoading)
       return;

    //after code when webview finishes
    NSLog(@"Webview loding finished");
 }

Swift 3 version:

func webViewDidFinishLoad(_ webView: UIWebView) {
    if webView.isLoading{
        return
    }
    print("Done loading")
}
Love Thailand

Try use:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)requestURL navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [requestURL URL];
NSLog(@"##### url = %@",[url absoluteString]); 
return YES;
}

don't forget to set your UIWebView Delegate

or add statement,

NSRange range = [[url absoluteString] rangeOfString:@"https://www.google.com"];
if (range.location != NSNotFound)
{}

hope to help you.

It is true that the original question was posted many years ago. Recently I had to find a reliable solution to this issue.

Here is the solution that worked for me:

  1. Replaced UIWebView with WKWebWiew.
  2. Added 'evaluateJavaScript' code while handling the 'didFinishNavigation' delegate method.

The complete code is:

   - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [webView evaluateJavaScript:@"document.body.innerHTML" completionHandler:^(id result, NSError *error) {
        if (result != nil) {
            // Call your method here
        }
        if(error) {
            NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
        }
    }];
}

If you aren't an owner of UIWebView and as a result you don't have an access to webViewDidFinishLoad but you have a reference to UIWebView you can use the next code

Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in

    guard uiWebView.isLoading else {
        return
    }

    timer.invalidate()
    //Add your logic here

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!