Search code examples
iosswiftyoutubeyoutube-apiytplayerview

iOS app with YouTube v3 API and youtube-ios-player-helper can't autoplay videos


I am having a problem autoplaying videos with the youtube-ios-player-helper pod provided by Google/YouTube. Here is the relevant part of my app (iOS 10, Swift 3):

  • a ChannelVideosViewController that displays video thumbnails as UIViews with an UITapGestureRecognizer that in turn segues to my PlayerViewController and passes the videoId from the API call
  • a PlayerViewController as follows:

    var youtubePlayerView = YTPlayerView() // player for videos
    var youtubeVideoID = String() // videoId from API passed by ChannelVideosViewController
    
    override func viewDidLoad() {
    // ... skipping UI stuff
    
    view.addSubview(youtubePlayerView)
    youtubePlayerView.load(withVideoId: youtubeVideoID, playerVars: ["autoplay":1,"modestbranding":1,"showinfo":0,"rel":0])
    }
    

With the code above the helper library successfully loads the videos and plays them in fullscreen when I press the "big red button" but I want to autoplay the videos directly after I segue into the view. Is there a way to do this?

  • "autoplay":1 from the YouTube docs doesn't seem to cut it for iOS.
  • youtubePlayerView.playVideo() doesn't do anything

Solution

  • Conform to YTPlayerViewDelegate protocol like this:

    self.youtubePlayer.delegate = self

    Now use this delegate method to play video automatically when player is ready:

    extension ViewController: YTPlayerViewDelegate {
        func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
            self.youtubePlayer.playVideo()
        }
    }
    

    It works perfectly in my case.