首页 > 解决方案 > 如何检测 AVplayer 并从 WKWebView 获取当前视频的 url?

问题描述

我正在使用下面的代码从UIWebView中提取 url :它工作正常,但是,用于WKWebView的相同代码不再工作了。谁能帮我?在 WKWebView 中播放的视频是 Inlineplacyback 而不是全屏。

我的代码是:

 NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemBecameCurrent(_:)), name: NSNotification.Name("AVPlayerItemBecameCurrentNotification"), object: nil)

 @objc func playerItemBecameCurrent(_ sender : NSNotification){
    let playerItem: AVPlayerItem? = sender.object as? AVPlayerItem
    if playerItem == nil {
        print("player item nil")
        return
    }
    // Break down the AVPlayerItem to get to the path
    let asset = playerItem?.asset as? AVURLAsset
    let url: URL? = asset?.url
    let path = url?.absoluteString

    print(path!,"video url")
}

回复网址:

https://r2---sn-po4g5uxa-5hql.googlevideo.com/videoplayback?txp=5531432&sparams=clen%2Cdur%2Cei%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn% 2Cms%2Cmv%2Cpcm2%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cexpire&ip=103.37.181.55&ratebypass=yes&id=o-AM9UWIaxopyYZX4gikGuswG8EMi3dhH_PPBMIqY5cbXj&expire=1554400796&c=MWEB&fvip=4&initcwndbps=481250&ipbits=0&mime=video%2Fmp4&dur=60.093&lmt=1554142002789460&key=yt6&mt=1554379078&itag= 18&source=youtube&gir=yes&requiressl=yes&signature=6C68366FC249958BB8E95A5D88074FF8BCB99745.DA113E66DD0B46863BAE52DAA3CAB31FD141F0E5&clen=2708520&mm=31%2C29&mn=sn-po4g5uxa-5hql%2Csn-cvh7knek&ei=vPGlXPOWHIWD8QOO1KBo&ms=au%2Crdu&pcm2=no&pl=24&mv=m&cpn=I9d32bNmeq3kf0jn&cver=2.20190403&ptk=youtube_none&pltype=contentugc

这是视频网址而不是网页网址,所以请帮助我如何获取它。谢谢。

标签: iosswiftavplayerwkwebview

解决方案


这是一种 hack,但我发现完成此操作的唯一方法。

首先将自己设置为 WKWebView 导航委托:

self.webView?.navigationDelegate = self

现在收听所有导航更改,并保存请求的 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)
    }

现在您只需要知道新屏幕何时可见,并使用您保存的 URL(要知道新可见屏幕的视频 URL)。

您可以通过收听UIWindowDidBecomeVisibleNotification通知来做到这一点:

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

然后检查导航窗口是否不是您的窗口,这意味着确实打开了一个新屏幕:

@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")
            }
        }
    }

推荐阅读