ios - 如何检测 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")
}
回复网址:
这是视频网址而不是网页网址,所以请帮助我如何获取它。谢谢。
解决方案
这是一种 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")
}
}
}
推荐阅读
- node.js - node.js 中的集群模块
- python - 如何根据字符串列表创建解密字典以按字符串加密
- javascript - 使用 React Navigation V5 进行身份验证,单击按钮无法指向时出错
- git - 如何为 Gitflow 开发架构
- python - 已解决 Python 和 Selenium,尝试在网站结果中接受 cookie:无法找到元素
- outlook - 为日历创建 Office 加载项时从哪里开始?
- python - 在 python 函数中更新数组的特定元素
- r - 如何计算R中每个日期的不同变量值的数量
- python - 在泊松分布中找到最大的非显着点积相似度
- python - 通过在 Spark 中列出该位置下的文件来避免“for 循环”