首页 > 解决方案 > 如何在 IOS Swift 上实现画中画 Webview?

问题描述

我是新的 swift,我想在 webview 中为 android、ios 实现画中画 (PiP)。我在这里找到了所有帖子并实现了一些代码:

对于 android ( https://stackoverflow.com/a/54061449/15311463 ) 它工作

对于 ios 不工作。我在 Xcode 中配置了 BackgourdMode 。我错过了什么?

private var pictureInPictureController: AVPictureInPictureController!
let source = """
                    document.addEventListener('click', function(e){
                        if (e.target.id === 'pip_mobile_btn_img') {
                            window.webkit.messageHandlers.iosListener.postMessage('true');
                        }
                    })
                """
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //self.performSegue(withIdentifier: "goToPlayer", sender: self)
        //print("Hello Thinh")
        if #available(iOS 14.2, *) {
          self.pictureInPictureController.canStartPictureInPictureAutomaticallyFromInline = true
          self.pictureInPictureController.startPictureInPicture()
        }
    }
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.allowsInlineMediaPlayback = true
        webConfiguration.mediaTypesRequiringUserActionForPlayback = []
        
        let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
        webConfiguration.userContentController.addUserScript(script)
        webConfiguration.userContentController.add(self, name: "iosListener")
        
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.scrollView.isScrollEnabled = false
        webView.isOpaque = true
        webView.scrollView.bounces = false

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
        
        let myRequest = URLRequest(url: URL(string: playerURL)!)
        webView.load(myRequest)
    }

标签: iosswift

解决方案


您可以获取或设置allowsPictureInPictureMediaPlayback您的 wkwebview 配置

WKWebViewConfiguration().allowsPictureInPictureMediaPlayback = true

用户可以在设置 > 常规 > 画中画 > 自动启动 Pip 中禁用画中画的自动调用。如果您认为您已正确设置所有内容,并且在按下主页按钮时发现您的视频没有进入画中画,请检查此设置。


推荐阅读