SWIFT - 检测WebView全屏视频进入和退出并处理

5
我希望能够在webview中检测视频全屏进入和退出,并在每种情况下执行一些代码。我需要捕获和处理哪些事件?观察者是否适用?对于我来说向用户显示某些选项并修改界面非常重要。
这里是我用于webview的部分代码。
请帮帮我,拯救我的一天。
 func loadWebSite() {
    let theConfiguration:WKWebViewConfiguration? = WKWebViewConfiguration()
    let thisPref:WKPreferences = WKPreferences()
    thisPref.javaScriptCanOpenWindowsAutomatically = true;
    thisPref.javaScriptEnabled = true
    theConfiguration!.preferences = thisPref;

    self.wkWebView = WKWebView(frame: self.getFrame(), configuration: theConfiguration!)


    self.wkWebView?.navigationDelegate = self
    self.wkWebView?.uiDelegate = self
    self.wkWebView?.bridge.printScriptMessageAutomatically = true
    self.wkWebView?.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
    self.wkWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    self.wkWebView?.addObserver(self, forKeyPath: "VideoExitFullScreen", options: .new, context: nil)
    self.wkWebView?.addObserver(self, forKeyPath: "VideoEnterFullScreen", options: .new, context: nil)


}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath == "loading") {
        self.backButton?.isEnabled = self.wkWebView!.canGoBack
        self.forwardButton?.isEnabled = self.wkWebView!.canGoForward
    } else if (keyPath == "estimatedProgress") {
        let estimatedProgress = Float(self.wkWebView!.estimatedProgress)
        if estimatedProgress > 0.90 {

        }
    }else if (keyPath == "VideoExitFullScreen") {
        // DO CODE HERE
    } else if (keyPath == "VideoEnterFullScreen") {
        // DO CODE HERE
    }
}

这里也有同样的问题。现在有解决方案了吗? - Tony Chen
1个回答

0

Swift

我想要的是在视频退出全屏时检测并重新播放。

NotificationCenter.default.addObserver(self, selector: #selector(onDidEnterFullscreen(_:)), name: UIWindow.didBecomeVisibleNotification, object: webview)
NotificationCenter.default.addObserver(self, selector: #selector(onDidLeaveFullscreen(_:)), name: UIWindow.didBecomeHiddenNotification, object: webview)

@objc func onDidEnterFullscreen(_ notification: Notification) {
      print("video is now playing in fullscreen")
}

@objc func onDidLeaveFullscreen(_ notification: Notification) {
      print("video has stopped playing in fullscreen")
      
      // This line plays the video again when exiting full screen
      webview?.evaluateJavaScript("var videos = document.getElementsByTagName(\"video\");  for (var i = 0; i < videos.length; i++) { videos.item(i).play(); };")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接