如何在IOS Swift上实现Picture in Picture Webview ?



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

for android (https://stackoverflow.com/a/54061449/15311463) It working

for 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)
}

您可以为您的wkwebviewconfiguration获取或设置allowsPictureInPictureMediaPlayback

WKWebViewConfiguration().allowsPictureInPictureMediaPlayback = true

用户可以在设置>一般比;图片中的图片>自动启动Pip。如果你认为你已经正确设置所有和发现你的视频不输入脉冲,当你按下按钮,检查这个设置。