12

How can I detect when my WKWebView is finished loading so that I can fetch the URL from it such as using the delegate method?

I implemented the delegate method for the WKWebView but I can't detect when it is finish loading the video.

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let preference = WKPreferences()
        preference.javaScriptEnabled = true
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preference
        webView = WKWebView(frame: view.bounds, configuration: configuration)
        view.addSubview(webView)

        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.load(URLRequest(url: URL(string: "http://www.youtube.com")!))
    }

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

But the method above is not called when it finishes loading the video from YouTube.

Thank you very much.

shim
  • 9,289
  • 12
  • 69
  • 108
Mustafa
  • 253
  • 1
  • 7
  • 15

1 Answers1

8

SWIFT 4:

Use following delegate method of WKNavigationDelegate. Where you can check is finished loading ?? And here you can get URL loaded in webView.

func webView(_ webView: WKWebView, didFinish  navigation: WKNavigation!) 
{
    let url = webView.url?.absoluteString
    print("---Hitted URL--->\(url!)") // here you are getting URL
}
Mayur Shinde
  • 412
  • 1
  • 6
  • 16
  • 2
    I think this method must be used for the start loading detection. And for the end: func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) – DmitryKanunnikoff Dec 11 '18 at 14:42
  • 3
    The delegate method you have used is called when the webView "begins" to receive content, not when its finished loading. The correct delegate method to use is "webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)" – SilentK Apr 29 '19 at 10:29