Autoplay YouTube videos in WKWebView with iOS 11

前端 未结 5 879
小鲜肉
小鲜肉 2020-12-17 17:19

I want to have small YouTube player in my app. The only way i found to be recommended is embeding web page with YouTube player into my app. So i used WKWebView and loaded em

相关标签:
5条回答
  • 2020-12-17 17:29

    It seems like the iframe API has changed since the time of the previous answer. I have updated the HTML that's loaded in the WKWebView based on the iframe API Reference. Using this code I managed to autoplay YouTube videos in fullscreen in a WKWebView on iOS11.

    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>
            """
        }
    }
    
    0 讨论(0)
  • 2020-12-17 17:29
    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)
    
    
    }
    

    Or Alternative you can use

    YTPlayer For Playing Youtube Video

    0 讨论(0)
  • 2020-12-17 17:32

    Xamarin Version

    -This can be added in view did load (hard-coding height). I also added "rel" for playerVars to only show related videos of my channel.

    The WKWebview is created dynamically and added to a container. The idea was for the iframe to fill the WKWebView and the WKWebView to fill the container. I could never set the height to 100% so it scaled depending of the device but seems that a hard-coded 640 height works well for most devices.

    I'm also passing the youtube id directly in a variable which is basically what videoURL.lastPathComponent returns. Auto-play works fine which is the main solution for this thread.

    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);
    
    0 讨论(0)
  • 2020-12-17 17:36

    For small Youtube MediaPlayer you can apply :-

    YourVideoView.configuration.allowsInlineMediaPlayback = true
    

    you can also do it from story board by check button on InLine Playback

    0 讨论(0)
  • 2020-12-17 17:53
    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"))
    
    0 讨论(0)
提交回复
热议问题