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

时间:2017-11-25 12:12:34

标签: ios swift youtube wkwebview

我想在我的应用中使用小型YouTube播放器。我发现推荐的唯一方法是将带有YouTube播放器的网页嵌入到我的应用中。所以我使用了WKWebView并使用自动播放参数加载了嵌入的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!))

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

6 个答案:

答案 0 :(得分:1)

似乎iframe API自上一个答案时间以来已发生变化。我已基于iframe API Reference更新了yearGroups = yearGroups.Take(yearGroups.Count() - 1).ToArray();中加载的HTML。使用此代码,我设法在iOS11上的cat foo.txt | grep -i "lat" | paste -d " " >> xyz.log中全屏播放YouTube视频。

WKWebView

答案 1 :(得分:1)

您可以将iframe与参数playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 }一起使用,以下是完整代码:

import UIKit
import WebKit

class ViewController: UIViewController {

let videoURL:URL = URL(string: "https://www.youtube.com/embed/695PN9xaEhs")!
@IBOutlet weak var myPlayer: WKWebView!
var didLoadVideo = false
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/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
    function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
    playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
    height: '\(myPlayer.frame.height)',
    width: '\(myPlayer.frame.width)',
    videoId: '\(videoURL.lastPathComponent)',
    events: {
    'onReady': onPlayerReady
    }
    });
    }

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

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
   if !didLoadVideo {
      myPlayer.loadHTMLString(embedVideoHtml, baseURL: nil)
      didLoadVideo = true
   }
  }
}

答案 2 :(得分:0)

var youTubeVideoHTML: String = "<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%@', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>"

func playVideoWithId(videoId: String) {
  var html: String = String(format: youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId)


}

或者您也可以使用

YTPlayer For Playing Youtube Video

答案 3 :(得分:0)

对于小型Youtube MediaPlayer,您可以应用:-

YourVideoView.configuration.allowsInlineMediaPlayback = true

您还可以通过在线播放中的选中按钮从故事板上进行操作

enter image description here

答案 4 :(得分:0)

Xamarin版本

-可以在视图加载后添加(硬编码高度)。我还为playerVars添加了“ rel”,使其仅显示与频道相关的视频。

WKWebview是动态创建的,并已添加到容器中。这个想法是让iframe填充WKWebView和WKWebView填充容器。我永远无法将高度设置为100%,因此它会根据设备的大小进行缩放,但似乎硬编码的640高度对于大多数设备都适用。

我还将youtube ID直接传递给一个变量,该变量基本上是 videoURL.lastPathComponent 返回的变量。 自动播放效果很好,这是该线程的主要解决方案。

var wkWebConfig = UIDevice.CurrentDevice.CheckSystemVersion(10, 0)
                    ? new WKWebViewConfiguration
                    {
                        MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None
                    }
                    : new WKWebViewConfiguration
                    {
                        MediaPlaybackRequiresUserAction = false
                    };

            _wkYoutubePlayer = new WKWebView(new CGRect(), wkWebConfig)
            {
                AccessibilityIdentifier = "viewPlayerYouTube",
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            viewPlayerContainerYouTube.AddSubview(_wkYoutubePlayer);

            NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Top, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Top, 1, 0).Active = true;
            NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Leading, 1, 0).Active = true;
            NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Trailing, 1, 0).Active = true;
            NSLayoutConstraint.Create(_wkYoutubePlayer, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, viewPlayerContainerYouTube, NSLayoutAttribute.Bottom, 1, 0).Active = true;

            var html = $"<!DOCTYPE html><html><body><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: '640', width: '100%', videoId: '{_youtubeVideoId}', playerVars: {{ rel: '0' }}, events: {{ 'onReady': onPlayerReady }} }}); }} function onPlayerReady(event) {{ event.target.playVideo(); }}</script></body></html>";
            _wkYoutubePlayer.LoadHtmlString(html, null);

答案 5 :(得分:-1)

let videoView = UIView(frame: CGRect(x: 0, y: 80, width: self.view.frame.width, height: self.view.frame.height - 80))
            self.view.addSubview(videoView)

let youTubeVideoHTML: String = "<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"https://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%@', events: { 'onReady': onPlayerReady} }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>"

let html: String = String(format: youTubeVideoHTML, videoView.frame.width, videoView.frame.height, id)


let webConfiguration = WKWebViewConfiguration()
if #available(iOS 9.0, *) {

     webConfiguration.allowsAirPlayForMediaPlayback = true
     webConfiguration.allowsInlineMediaPlayback = true
     webConfiguration.allowsPictureInPictureMediaPlayback = true
     webConfiguration.mediaTypesRequiringUserActionForPlayback = []

}

webView = WKWebView(frame: CGRect(x: 0, y: 0, width: videoView.frame.width, height: videoView.frame.height), configuration: webConfiguration)
webView.uiDelegate = self
webView.scrollView.isScrollEnabled = false
webView.scrollView.zoomScale = 0
webView.isMultipleTouchEnabled = false
webView.scrollView.isPagingEnabled = false
webView.scrollView.isMultipleTouchEnabled = false
videoView.addSubview(webView)

webView.loadHTMLString(html, baseURL: URL(string: "https://www.youtube.com"))