swift 如何检测AVplayer并从WKWebView获取当前视频的URL?

j13ufse2  于 2022-10-31  发布在  Swift
关注(0)|答案(6)|浏览(266)

我正在使用以下代码从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")
}

回应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
这是视频网址不是网页网址,所以,请帮助我如何得到这个。谢谢。

c9qzyr3d

c9qzyr3d1#

这是一种黑客,但唯一的方法,我发现完成这一点。

  • 首先将自己设置为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")
            }
        }
    }
dsekswqp

dsekswqp3#

从WKNavigationDelegate的webView(_:decidePolicyFor:decisionHandler:)方法中的导航操作的请求属性检索完整URL。

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if let urlStr = navigationAction.request.url?.absoluteString {
        //urlStr is your URL
    }

    decisionHandler(.allow)
}

也别忘了遵守协议

webView.navigationDelegate = self
9gm1akwq

9gm1akwq4#

使用SWIFT

您可以使用以下代码从webview的url获取html内容

let docString = webView.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")

在这种情况下,您将获得整个html内容,
然后查找html字符串中的href链接

let regex = try! NSRegularExpression(pattern: "<a[^>]+href=\"(.*?)\"[^>]*>")
let range = NSMakeRange(0, docString.characters.count)
let matches = regex.matches(in: docString, range: range)
for match in matches {
    let htmlLessString = (docString as NSString).substring(with: match.rangeAt(1))
    print(htmlLessString)
}

检查它是否是youtube网址使用
一般表示式:“”“”“”“
另一种实现方式
"跳出框框思考"
你可以调用一个api来获取url,这看起来很容易,使用像php,.net等网络语言。
在PHP中获取网页内所有URL的代码(使用任何适合你的语言)

$url="http://wwww.somewhere.com";
$data=file_get_contents($url);
$data = strip_tags($data,"<a>");
$d = preg_split("/<\/a>/",$data);
foreach ( $d as $k=>$u ){
    if( strpos($u, "<a href=") !== FALSE ){
        $u = preg_replace("/.*<a\s+href=\"/sm","",$u);
        $u = preg_replace("/\".*/","",$u);
        print $u."\n";
    }
}

要逐一检查是否是youtube网址。

$sText =  "Check out my latest video here http://www.youtube.com/?123";
preg_match_all('@https?://(www\.)?youtube.com/.[^\s.,"\']+@i', $sText, $aMatches);
var_dump($aMatches);

如果您想检查示例应用程序是否使用了相同的方法,请获取一个Web调试代理并对其进行深入研究
以上许多解释都来自其他网站。
我希望它能满足你的需要!编码快乐!

3yhwsihp

3yhwsihp5#

在ViewController中尝试以下操作,在WKWebView上添加一个URL观察器:

override func loadView() {
    let webConfig = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero, configuration: webConfig)
    webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
    view = webView
}

覆盖observeValue以获取url请求:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == #keyPath(WKWebView.url) {
        let urlRequest:String = webView.url?.absoluteString ?? ""
        print(urlRequest)
    }
}

最后...取消初始化观察者:

deinit { webView.removeObserver(self, forKeyPath: "URL") }
tvmytwxo

tvmytwxo6#

在WKWebView中,我们需要添加Inlineplacyback的配置。如果在WKWebView中设置了该配置,则它将自动进入全屏视图。
以下代码供参考:

class WebViewController: UIViewController {

  lazy var webView: WKWebView! = {

    let webView = WKWebView(frame: .zero, configuration: configuration)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.uiDelegate = self
    webView.navigationDelegate = self
    let request = URLRequest(url: .init(string: "https://developer.apple.com/videos/play/wwdc2020/10188/")!)
    webView.load(request)
    return webView

  }()

  lazy var configuration: WKWebViewConfiguration! = {
    let configuration = WKWebViewConfiguration()
    configuration.allowsInlineMediaPlayback = true
    configuration.mediaTypesRequiringUserActionForPlayback = .audio
    configuration.allowsPictureInPictureMediaPlayback = true
    return configuration
  }()

  override func loadView() {
    super.loadView()

    self.view.backgroundColor = .white
    self.view.addSubview(self.webView)

    // Constraint

    NSLayoutConstraint.activate([

      self.webView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
      self.webView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
      self.webView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
      self.webView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),

    ])

  }

}

extension WebViewController: WKUIDelegate{

}

extension WebViewController: WKNavigationDelegate{

  func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse) async -> WKNavigationResponsePolicy {
    debugPrint("---------------------------- decidePolicyFor navigationResponse")
    return .allow
  }

  func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
    debugPrint("---------------------------- decidePolicyFor navigationAction")
    decisionHandler(.allow, .init())
  }

}

Click here以查看输出视频示例

相关问题