Tameem
Tameem

Reputation: 21

Detect when the WebView finishes loading in Swift4?

I want to display progress while the WebView is loading and dismiss it when the WebView finishes loading. I tried this code:

import UIKit
import WebKit
import SVProgressHUD
class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet var WebView1: WKWebView!
@IBOutlet var WebView2: WKWebView!


let YouTubeURL = URL (string: "https://www.youtube.com/")


@IBAction func YTButtonAction(_ sender: Any) {

    let YTRequest = URLRequest(url: YouTubeURL!)
    WebView1.load(YTRequest)
    if WebView1.isLoading {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(WebView1 : UIWebView) {

        SVProgressHUD.dismiss()

    }


}
}

But it doesn't work. The progress continue rotating. Anybody knows how to solve this problem?

Upvotes: 0

Views: 3111

Answers (2)

Tameem
Tameem

Reputation: 21

The answer : I changed

  1. UIWebViewDelegate to WKNavigationDelegate

  2. WebView1.delegate = self to WebView1. navigationDelegate = self The name of the WKWebView property is navigationDelegat

  3. func webViewDidFinishLoad(WebView1 : UIWebView) to func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

Upvotes: 0

vadian
vadian

Reputation: 285064

Three fatal issues:

  • You have to set the delegate

    WebView1.delegate = self
    
  • The signature of the delegate method is wrong

    func webViewDidFinishLoad(_ webView: UIWebView)
    
  • The delegate method must be on the top level of the class.

I think there is a fourth fatal issue: I doubt that WKWebView conforms to UIWebViewDelegate at all. I suppose you have to adopt WKNavigationDelegate and implement webView(:didFinish:) instead.

And please conform to the Swift naming convention that variable and function / method names start with a lowercase letter.

Upvotes: 5

Related Questions