How to detect AVplayer and get url of current video from WKWebView?

This is kind of a hack, but the only way I found to accomplish this.

First set yourself as WKWebView navigation delegate:

self.webView?.navigationDelegate = self

Now listen to all navigation changes, and save the requested url:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let urlStr = navigationAction.request.url?.absoluteString {
            //Save presented URL
            //Full path can be accessed via self.webview.url
        }

        decisionHandler(.allow)
    }

Now you only need to know when does the new screen become visible, and use the URL you saved (To know the video URL of the new visible screen).

You can do this via listening to UIWindowDidBecomeVisibleNotification notification:

NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeVisibleNotification(notif:)), name: NSNotification.Name("UIWindowDidBecomeVisibleNotification"), object: nil)

Then check if the navigation window is not your window, and that means a new screen did open:

@objc func windowDidBecomeVisibleNotification(notif: Notification) {
        if let isWindow = notif.object as? UIWindow {
            if (isWindow !== self.view.window) {
            print("New window did open, check what is the currect URL")
            }
        }
    }

Leave a Comment