Search code examples
iosswiftxcodeyoutubeuiwebview

How to autoplay a YouTube video in a UIWebView swift


I'm having an issue trying to autoplay my UIWebView.

here's my code:

WebVideo.allowsInlineMediaPlayback = true
WebVideo.mediaPlaybackRequiresUserAction = false

WebVideo.loadHTMLString("<iframe width=\"\(WebVideo.frame.width)\" height=\"\(WebVideo.frame.height)\" src=\"\(thumbnail)?playsinline=1\" frameborder=\"0\" allowfullscreen & autoplay=1 &showinfo=0 &controls=0 autohide=1></iframe>", baseURL: nil)

now This does not work. and I tried with this code too:

 WebVideo.allowsInlineMediaPlayback = true
 WebVideo.mediaPlaybackRequiresUserAction = false

 WebVideo.loadHTMLString("<iframe width=\"\(WebVideo.frame.width)\" height=\"\(WebVideo.frame.height)\" src=\"\(thumbnail)&autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil)

It does not work either

Can you help me, how do I autoplay..?


Solution

  • I also faced similar issue and ended up using helper Library of Google

    https://github.com/youtube/youtube-ios-player-helper

        let player = YTPlayerView(frame: CGRect(0,0,view.frame.width , 300))
        let dict = ["modestbranding" : 0,"controls" : 1 ,"autoplay" : 1,"playsinline" : 1,"autohide" : 1,"showinfo" : 0]
        player.loadWithVideoId("video-ID" ,playerVars: dict)
        player.delegate = self
    

    Call this delegate function then

    func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
        playerView.playVideo()
    
    }