12
votes

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 embed YouTube player page with autoplay parameter: https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1.

Code would be like:

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!))

This embed player url autoplays in desktop Safari, but does not autoplay in mobile Safari or WKWebView. Can i force WKWebView to autoplay video somehow? Or use another YouTube player url?

5
Wasn't Apple blocking autoplay on video's?Riyan Fransen
Yes, in Safari, but I think you should be able to autoplay in your app.Ondra
Found the solution?Ankit Kumar Gupta

5 Answers

1
votes

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
votes

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
votes
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"))
-2
votes
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

-2
votes

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

enter image description here