Play Youtube video in AVPlayerViewController in Swift

Ok, so I'm looking to play movie trailers in my application. The user will press a button and then play the video. I added import AVKit and import AVFoundation to my file. This is the code that I still did to play the video:

 @IBAction func playTrailerPressed(sender: AnyObject) { let videoURL = NSURL(string: "https://youtu.be/d88APYIGkjk") let player = AVPlayer(URL: videoURL!) let playerViewController = AVPlayerViewController() playerViewController.player = player self.presentViewController(playerViewController, animated: true) { playerViewController.player!.play() } } 

It seems to be launching AVPlayerViewController , but not playing YouTube videos. Instead, I get the following:

enter image description here

I tried the sharing and attachment link with YouTube but did not work. If I use the link that has the name of the video file at the end, it plays perfectly, for example: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" - so I know that the code works.

Does anyone know if this method can be used with a YouTube video? (I also tried trailers from IMDb and Apple, but this is the same).

Thank you for your help!

+5
source share
1 answer

AVPlayer only plays video files, and YouTube videos are not directly displayed as movie files at their URL. It seems like the preferred way to handle YouTube videos is to incorporate the web view into your application. See this page for information from Google on how to do this.

+10
source

Source: https://habr.com/ru/post/1240282/


All Articles