How to play YouTube content on tvOS

Carl Thomas picture Carl Thomas · Sep 11, 2015 · Viewed 12.3k times · Source

How would one play a YouTube video on Apple tvOS?

YouTube's embed feature works in iOS 9 as the OS has a UIWebView we can embed it into. The new tvOS does not include a UIWebView so I cannot see a way to embed the YouTube video.

Answer

Daniel Storm picture Daniel Storm · Sep 12, 2015

UIWebView and MPMoviePlayerController are not available for tvOS. Our next option is to use AVPlayer to play YouTube videos.

AVPlayer cannot play a YouTube video from a standard YouTube URL, ie. https://www.youtube.com/watch?v=8To-6VIJZRE. It needs a direct URL to the video file. Using HCYoutubeParser we can accomplish exactly that. Once we have the URL we need, we can play it with our AVPlayer like so:

NSString *youTubeString = @"https://www.youtube.com/watch?v=8To-6VIJZRE";
NSDictionary *videos = [HCYoutubeParser h264videosWithYoutubeURL:[NSURL URLWithString:youTubeString]];
NSString *urlString = [NSString stringWithFormat:@"%@", [videos objectForKey:@"medium"]];
AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:urlString]];

AVPlayerItem *avPlayerItem = [[AVPlayerItem alloc]initWithAsset:asset];
AVPlayer *videoPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:videoPlayer];
avPlayerLayer.frame = playerView.layer.bounds;
[playerView.layer addSublayer:avPlayerLayer];

[videoPlayer play];

Note that this is NOT allowed under YouTube's TOS. Use it at your own risk. Your app may stop working at any point if YouTube notices you are not following the TOS or if YouTube changes the embed code it generates.