我正在iOS上尝试以下代码以嵌入YouTube视频UIWebView
:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0"></iframe>
<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', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
</script>
</body>
</html>
我使用以下 Swift 代码来完成它:
let html = "<!DOCTYPE html><html><head><style type="text/css"> body { margin: 0; padding: 0; } body, html { height: 100%; width: 100%; } </style> </head> <body> <iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0"></iframe> <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', { events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body></html>"
let width = UIScreen.mainScreen().bounds.width
let height = UIScreen.mainScreen().bounds.height
youTubeWebView = UIWebView(frame: CGRectMake(20, 120, width - 40, height-500))
youTubeWebView.mediaPlaybackRequiresUserAction = false
view.addSubview(youTubeWebView)
youTubeWebView.loadHTMLString(html, baseURL: NSBundle.mainBundle().resourceURL)
但是,尽管视频加载了,但它实际上并没有像预期的那样自动播放。
试着把?rel=0&autoplay=1
<iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?rel=0&autoplay=1" frameborder="0"></iframe>
希望能解决您的问题。
顺便说一句:无法在IOS/移动设备中完成
"警告:为了防止用户通过蜂窝网络进行未经请求的下载,嵌入式媒体无法在iOS上的Safari中自动播放 - 用户始终启动播放。https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations