Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when WKWebView is finished loading

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.

like image 597
Mustafa Avatar asked Mar 14 '17 21:03

Mustafa


People also ask

How do I know if WKWebView finished loading Swift?

To check if your WKWebView has loaded easily implement the following method: import WebKit import UIKit class ViewController: UIViewController, WKNavigationDelegate { let webView = WKWebView() func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

How can I clear the contents of a UIWebView WKWebView?

To clear old contents of webview With UIWebView you would use UIWebViewDelegate 's - webViewDidFinishLoad: .

What is WKWebView in Swift?

A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.


1 Answers

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
}
like image 140
Mayur Shinde Avatar answered Oct 13 '22 13:10

Mayur Shinde