gpt4 book ai didi

ios - 使用 iOS 11 在 WKWebView 中自动播放 YouTube 视频

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:37 32 4
gpt4 key购买 nike

我想在我的应用中安装小型 YouTube 播放器。我发现推荐的唯一方法是将带有 YouTube 播放器的网页嵌入到我的应用程序中。所以我使用了 WKWebView 并使用 autoplay 参数加载了嵌入的 YouTube 播放器页面:https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1

代码如下:

let webConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
let youtubeURL = URL(string: "https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1")
webView.load(URLRequest(url: youtubeURL!))

此嵌入播放器 url 在桌面 Safari 中自动播放,但在移动 Safari 或 WKWebView 中不自动播放。我可以强制 WKWebView 以某种方式自动播放视频吗?或者使用其他 YouTube 播放器网址?

最佳答案

自上次回答以来,iframe API 似乎发生了变化。我已经根据 iframe API Reference 更新了加载到 WKWebView 中的 HTML .使用此代码,我设法在 iOS11 上的 WKWebView 中全屏自动播放 YouTube 视频。

class YouTubeVideoPlayerVC: UIViewController {

@IBOutlet weak var videoPlayerView: WKWebView!
var videoURL:URL! // has the form "https://www.youtube.com/embed/videoID"
var didLoadVideo = false

override func viewDidLoad() {
super.viewDidLoad()
videoPlayerView.configuration.mediaTypesRequiringUserActionForPlayback = []
}

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Size of the webView is used to size the YT player frame in the JS code
// and the size of the webView is only known in `viewDidLayoutSubviews`,
// however, this function is called again once the HTML is loaded, so need
// to store a bool indicating whether the HTML has already been loaded once
if !didLoadVideo {
videoPlayerView.loadHTMLString(embedVideoHtml, baseURL: nil)
didLoadVideo = true
}
}

var embedVideoHtml:String {
return """
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '\(videoPlayerView.frame.height)',
width: '\(videoPlayerView.frame.width)',
videoId: '\(videoURL.lastPathComponent)',
events: {
'onReady': onPlayerReady
}
});
}

function onPlayerReady(event) {
event.target.playVideo();
}
</script>
</body>
</html>
"""
}
}

关于ios - 使用 iOS 11 在 WKWebView 中自动播放 YouTube 视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47485833/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com