50

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.

Joel Farris
  • 510
  • 1
  • 6
  • 23
Carl Thomas
  • 3,605
  • 6
  • 38
  • 50
  • Have you seen? http://stackoverflow.com/questions/32493872/how-do-i-play-a-video-on-tvos-for-apple-tv/32551565#32551565 Just swap the url in 'launchPlayer' to your YouTube url. – Alex Hedley Sep 14 '15 at 17:24
  • 6
    I'm guessing we're going to need a library from Google to do this without violating the Terms of Service. So it might be a few months while they build this up (along with their own YouTube tvOS app which will come first obviously). – Nick Sep 16 '15 at 19:45
  • Plex is able to play YouTube and Vimeo videos from their new [AppleTV App](https://blog.plex.tv/2015/11/02/plex-on-the-new-apple-tv/) via their [Watch Later / Plex It feature](https://support.plex.tv/hc/en-us/articles/200392326-Using-the-Plex-It-Bookmarklet). Based on a quick poke some of their [GitHub souce](https://github.com/plexinc-plugins/Services.bundle/blob/master/Contents/Service%20Sets/com.plexapp.plugins.youtube/URL/YouTube/ServiceCode.pys), it appears they're just doing page scraping. Is that correct? How do they get away with this or has no one noticed? – Nick Nov 03 '15 at 07:48
  • @nickv2002 *How do they get away with this or has no one noticed?* Not sure if this is exactly *illegal*, but its frowned upon. At the moment this is the only option if you want to play YouTube/Vimeo content. – Daniel Storm Nov 11 '15 at 13:57
  • @DanielStorm I was just surprised this worked because the've been on the iOS app store for a while. Better that we have these workarounds if YouTube doesn't provide an API though. – Nick Nov 11 '15 at 19:46
  • this might do more than simply violate their terms of service; I thought users retained their ownership/copyright? if so, and the video is monetized with ads which many videos are then the video owner could potentially sue you for loss of revenue since the ads are missing. – Nostradamus Jul 05 '16 at 17:27
  • You can find solution at http://stackoverflow.com/questions/37020490/play-youtube-videos-from-my-tvos-application/38764151#38764151 . – Roman Podymov Aug 25 '16 at 06:50

7 Answers7

46

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.

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
  • 2
    Is HCYoutubeParser still being supported? Doesn't seem to work for me – Shazam Sep 28 '15 at 00:32
  • 1
    @Shazam it has not been updated in over 2 years on GitHub so some issues may exist. – Daniel Storm Oct 06 '15 at 12:39
  • Know any library that can run on tvOS? Like GTLYouTube or something? – Mayur Deshmukh Oct 11 '15 at 13:59
  • @MayurDeshmukh at the moment, no. All iOS YouTube players use a `UIWebView` so they are not applicable for tvOS. I'd anticipate that YouTube will release it's own library for tvOS at some point as they've done for iOS [here](https://developers.google.com/youtube/v3/guides/ios_youtube_helper). – Daniel Storm Oct 11 '15 at 14:04
  • 1
    Can anyone point me to part of YouTube docs that is violated by this libraries? – Vitalii Boiarskyi Oct 19 '16 at 14:27
  • How exactly does Youtube ban the app from working? Since there is not an API key. IP address perhaps? – WrightsCS Jun 13 '19 at 22:10
18

Swift 2.0 version of Daniel Storm's answer:

let youTubeString : String = "https://www.youtube.com/watch?v=8To-6VIJZRE"
let videos : NSDictionary = HCYoutubeParser.h264videosWithYoutubeURL(NSURL(string: youTubeString))
let urlString : String = videos["medium"] as! String
let asset = AVAsset(URL: NSURL(string: urlString)!)

let avPlayerItem = AVPlayerItem(asset:asset)
let avPlayer = AVPlayer(playerItem: avPlayerItem)
let avPlayerLayer  = AVPlayerLayer(player: avPlayer)
avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height);
self.view.layer.addSublayer(avPlayerLayer)
avPlayer.play()
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
Burf2000
  • 5,001
  • 14
  • 58
  • 117
  • 2
    How did you set up HCYoutubeParser to import into Swift? Tried with CocoaPods but the `use_frameworks!` stuff breaks my existing Obj-C code. – Nick Dec 05 '15 at 01:51
8

XCDYouTubeKit has been a popular way to directly play a YouTube video on iOS for a while, and the developer recently updated it to support the new AppleTV.

Here's the code from the Objective-C example:

AVPlayerViewController *playerViewController = [AVPlayerViewController new];
[self presentViewController:playerViewController animated:YES completion:nil];

__weak AVPlayerViewController *weakPlayerViewController = playerViewController;
[[XCDYouTubeClient defaultClient] getVideoWithIdentifier:playlistItem.snippet.resourceId.videoId completionHandler:^(XCDYouTubeVideo * _Nullable video, NSError * _Nullable error) {
    if (video)
    {
        NSDictionary *streamURLs = video.streamURLs;
        NSURL *streamURL = streamURLs[XCDYouTubeVideoQualityHTTPLiveStreaming] ?: streamURLs[@(XCDYouTubeVideoQualityHD720)] ?: streamURLs[@(XCDYouTubeVideoQualityMedium360)] ?: streamURLs[@(XCDYouTubeVideoQualitySmall240)];
        weakPlayerViewController.player = [AVPlayer playerWithURL:streamURL];
        [weakPlayerViewController.player play];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}];

Swift example here.

Nick
  • 3,172
  • 3
  • 37
  • 49
  • If you're trying to play YT content from a TVML/TVJS interface, here's [a Gist that shows how](https://gist.github.com/nickv2002/b7bb28cdccc000bdb910). – Nick Dec 15 '15 at 23:51
  • This will also violate the youtube TOS, wouldn't it? – Tobonaut Jan 25 '16 at 19:10
  • 2
    Yes, XCDYouTubeKit does. See also: [Discussion of Apple approval for apps using XCDYouTubeKit](https://github.com/0xced/XCDYouTubeKit/issues/121) – Nick Jan 25 '16 at 19:22
5

Sadly, even an Apple Staff person echoed the “negative” on this. From an Apple Developer Forums thread on the topic:

There is no support for WebViews on tvOS, and so an iframe implementation will not work. TVML does not offer this capability.

Joel Farris
  • 510
  • 1
  • 6
  • 23
4

After some trying I'm happy to announce that:

youtube://watch/video_id

will open the YouTube app and play the YouTube video.

Enjoy.

Matteo Gobbi
  • 17,697
  • 3
  • 27
  • 41
  • Thanks! This is probably currently the only reliable solution on tvOS. – Ely Sep 07 '20 at 17:04
  • Unfortunately, someone didn't understand it, since my answer (which came from my investigation and tests) -1ed my answer. Glad it helped you. – Matteo Gobbi Sep 07 '20 at 23:18
1

As an addition to Daniel Storm's answer, you can also achieve this with the new TVML language using the code:

<lockup videoURL="http://mp4-url.mp4">
<img src="video thumbnail.jpg" />
</lockup>

(for this to work you'll need the direct video file (mp4) which also is not allowed by the Youtube TOS)

EDIT, found also the .JS solution: How do I play a video on tvOS for Apple TV?

Community
  • 1
  • 1
Bldjef
  • 138
  • 10
0

I used this one https://cocoapods.org/pods/youtube-parser

Youtube.h264videosWithYoutubeURL(testURL) { (videoInfo, error) -> Void in
    if let videoURLString = videoInfo?["url"] as? String,
         videoTitle = videoInfo?["title"] as? String {
             print("\(videoTitle)")
             print("\(videoURLString)")
             self.playVideo(videoURLString)
    }
}
pillade
  • 11
  • 1
  • 2