How to autoplay youtube video in WKWebView?
Asked Answered
H

3

9

I have written a code to play youtube video in WKWebView. I want to autoplay video when a screen is loaded also the inline video should play not in the new screen. Below is my code.

 @IBOutlet weak var myPlayer: WKWebView!
 override func viewDidLoad() {
    super.viewDidLoad()

    if let videoURL:URL = URL(string: 
    "https://www.youtube.com/embed/695PN9xaEhs?playsinline=1") {
    let request:URLRequest = URLRequest(url: videoURL)
    myPlayer.load(request)
  }
 }

I have set configuration for WKWebView in Interface builder.

Interface Builder Attribute Properties

enter image description here

Can anyone provide a suggestion to play it automatically when the view is loaded?

Hein answered 11/4, 2019 at 6:41 Comment(4)
Possible duplicate of Autoplay YouTube videos in WKWebView with iOS 11Austerity
Also a possible duplicate of this - #15718254Noose
Yes, but I wanted to play in inline and autoplay.Hein
I have raised flag for this. Thanks.Hein
T
8

Use iFrame to load a video on WKWebview and write the script to autoplay video. see the following code.

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', {
        playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
        height: '\(videoPlayerView.frame.height)',
        width: '\(videoPlayerView.frame.width)',
        videoId: '\(videoURL.lastPathComponent)',
        events: {
        'onReady': onPlayerReady
        }
        });
        }

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

See the following post for more info Autoplay YouTube videos in WKWebView with iOS 11

Tupi answered 11/4, 2019 at 6:47 Comment(4)
Thanks atul, it is worked but one problem is there, I want to play it inline. How can we do that?Hein
I have set allowsInlineMediaPlayback = true. but not worked.Hein
Atul found solution we have to add parameter in 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 } }); }Hein
Okay, Good, I have updated my answer as you suggested a solution, accept this answer thanks.Tupi
H
8

Make sure to pass the configuration at the creation of web view. Like this:

let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = []
let webView = WKWebView(frame: .zero, configuration: configuration)
Herrah answered 11/4, 2019 at 6:47 Comment(2)
This config, along with autoplay in a URL like https://www.youtube.com/embed/RRxQQxiM7AA?autoplay=1, is not autoplaying. Can anyone confirm this works for them?Hitherward
no, it's not workingWakeup
T
8

Use iFrame to load a video on WKWebview and write the script to autoplay video. see the following code.

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', {
        playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
        height: '\(videoPlayerView.frame.height)',
        width: '\(videoPlayerView.frame.width)',
        videoId: '\(videoURL.lastPathComponent)',
        events: {
        'onReady': onPlayerReady
        }
        });
        }

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

See the following post for more info Autoplay YouTube videos in WKWebView with iOS 11

Tupi answered 11/4, 2019 at 6:47 Comment(4)
Thanks atul, it is worked but one problem is there, I want to play it inline. How can we do that?Hein
I have set allowsInlineMediaPlayback = true. but not worked.Hein
Atul found solution we have to add parameter in 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 } }); }Hein
Okay, Good, I have updated my answer as you suggested a solution, accept this answer thanks.Tupi
C
-2

mediaTypesRequiringUserActionForPlayback

//Determines which media types require a user gesture to begin playing.
var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes

Just set empty array for this property to auto-play.

Candidate answered 11/4, 2019 at 6:51 Comment(1)
Bro, I tried this before, I don't know why it's not working.Hein

© 2022 - 2024 — McMap. All rights reserved.