7

I have a UITableView full of thumbnails of YouTube videos, and when they tap on one I want to start playing the YouTube video full screen automatically without the user seeing a view being added or having to interact any further than tapping the thumbnail.

Basically, I don't want to see the YouTube video player with that red play icon at all.

I was planning to use youtube-ios-player-helper/YTPlayerView to accomplish this, and I understand it just employs a UIWebView but I can't seem to figure out how to get it to work.

If I create an instance variable on my class, set myself as the delegate and select a random video for watching:

let YouTubePlayer = YTPlayerView()

override func viewDidLoad() {
    super.viewDidLoad()

    YouTubePlayer.delegate = self
    YouTubePlayer.loadWithVideoId("apKJikXWU2g")

    ...
}

and then when the delegate method gets called:

func playerViewDidBecomeReady(playerView: YTPlayerView!) {
    YouTubePlayer.playVideo()
}

But most of the time it either crashes in my AppDelegate with this message:

Nov 5 23:34:44 rtcreporting[73827] : logging starts...

Nov 5 23:34:44 rtcreporting[73827] : setMessageLoggingBlock: called

Or it will work if I disable breakpoints but I get a ton of Auto Layout constraint complaint messages before the video plays, indicating something is angry on some level.

Is this because I'm using a UIView subclass without actually adding it to the view hierarchy?

How would I accomplish the behaviour of autoplaying a YouTube video after a certain event without revealing a kludgy intermediary view?

Community
  • 1
  • 1
Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • I recall building an iPad app where we embed the Youtube video within a webview, when we tapped on the video, it automagically expands to fullscreen for us. – Zhang Nov 06 '14 at 04:05
  • Could you elaborate? – Doug Smith Nov 06 '14 at 04:51
  • Maybe try this: http://stackoverflow.com/questions/9060153/play-youtube-videos-in-iphone-app-without-using-uiwebview (You'll need to modify it a bit so that you would have a webview in each of your tableViewCell as the thumbnail) – Zhang Nov 06 '14 at 06:09
  • I recommend using Youtube Data API: https://developers.google.com/youtube/v3/getting-started for the proper way to do it. – Zhang Nov 07 '14 at 03:55
  • youtube data api is managing video, not playing.. using Youtube iOS Helper Library with a custom view on top of the playerView might suit your case – Mia Jul 02 '15 at 08:35
  • @Doug, have you figured this out?....I'm doing pretty much the same thing, but I cant get autoplay to work when user clicks on thumbnail. It brings them to another view with the youtube player, and they are force to tap the play button again to play. Let me know please. – Pangu Feb 22 '16 at 16:20

3 Answers3

7

Here you go, you don't have to see the youtube logo.

  1. Define youtube iFrame, You'll need to replace the '%@' part with your youtube Video ID later when you supply to a UIWebView

    #define  youtubeVideoPlayUrl
    @"<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%f', height:'%f', videoId:'%@', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>"
    
  2. Define a UIWebView object of name videoWebView to display the iFrame. You can set the height and width to be zero so it doesn't block your screen. It's like a hidden iFrame.

    self.videoWebview = [UIWebView alloc] init];
    
  3. I suggest you to use your own default Image and a play button on top of the image to avoid having to show 'Youtube' video logo. Once you've done that, use the following code to play the youtube video full screen

    - (void)onPlayYouTubeVideo:(UIButton *)sender
    {
     NSString *youtubeVideoID = YOUR_YOUTUBE_VIDEO_ID;    
     NSString *html = [NSString stringWithFormat:youtubeVideoPlayUrl, 
     _videoWebView.frame.size.width, _videoWebView.frame.size.height, youtubeVideoID];
     _videoWebView.mediaPlaybackRequiresUserAction = NO;
    _videoWebView.delegate = self;
    [_videoWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
    }
    

I'm using like this for a hotel booking app.

Suraj Pathak
  • 910
  • 8
  • 9
5

I've created a demo app for you.

Source code to load webView html taken from: http://iphoneincubator.com/blog/audio-video/how-to-play-youtube-videos-within-an-application

ViewController header file

@interface ViewController : UIViewController

@property (nonatomic, strong) UIWebView *webView;

@end

ViewController implementation file

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
    self.webView.layer.borderWidth = 1.0;
    self.webView.layer.borderColor = [UIColor redColor].CGColor;

    self.webView.backgroundColor = [UIColor blackColor];

    self.webView.center = self.view.center;

    [self.view addSubview:self.webView];




    NSString* embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
        background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";

    NSURL *url = [NSURL URLWithString:@"https://www.youtube.com/watch?v=K14RnTVt194"];

    NSString* html = [NSString stringWithFormat:embedHTML, url, self.webView.frame.size.width, self.webView.frame.size.height];

    [self.webView loadHTMLString:html baseURL:nil];
}

You should see this:

screenshot of demo app

When you press the play button it goes full screen.

You probably want to create a method that accepts a URL to the youtube video in your custom cell class.

Then in the cellForRowAtIndexPath: method of your View Controller, you can call your custom cell loadYouTubeVideoWithURL: method to load the Youtube video url from your data source.

Zhang
  • 11,549
  • 7
  • 57
  • 87
  • The only thing about that is I still see the YouTube video player. I want to only see the thumbnail as say a UIImageView I can tap, similar to how the [Jasmine app](https://itunes.apple.com/app/jasmine-youtube-client/id554937050?mt=8) or [iTube](https://itunes.apple.com/us/app/itube-free-playlist-manager/id559788663?mt=8) does it. How would I achieve that? – Doug Smith Nov 06 '14 at 13:50
  • You can overlay a UIImageView ontop of your UIWebView. Try and extract the video ID from your youtube video URL (e.g. "K14RnTVt194" in https://www.youtube.com/watch?v=K14RnTVt194) using NSString methods. When user taps on the thumbnail, the taps is ignored by imageView and the webView behind handles the tap, and begins to play the video. Maybe you should be using Youtube's Data API to do it instead: https://developers.google.com/youtube/v3/ It seems like the proper way instead of our hack jobs here :D – Zhang Nov 07 '14 at 03:51
  • That's an interesting solution, but seems slightly hacky, I'd like to hear other possible solutions before trying that. – Doug Smith Nov 09 '14 at 06:58
  • you can create a overlay as suggested but instead of an image a button which will trigger the youtube play() function to get call and will launch the video player.. not sure if this is what you want.. :) – valbu17 Nov 14 '14 at 04:32
  • Also, for what I see in Jasmine looks like they are using their own "image" for the video and on top some buttons which trigger the player.. the it will be for the button bellow called play video.. The youtube helper allows you to create buttons to trigger the player play and go to full screen if you set the player parameters to not play inline. – valbu17 Nov 14 '14 at 04:34
3

The YouTube Helper Library is definitely a nice way to embed Youtube in your iOS application while following YouTube's Terms of Service.

Regarding the Auto Layout constraints log warnings,

Is this because I'm using a UIView subclass without actually adding it to the view hierarchy?

These errors have nothing to do with your implementation and are easily reproducible.

You can create an empty iOS 8 project, add a UIWebView in your interface and try to load a Youtube page.

[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUTUBE_URL"]]];

You'll get the same Auto Layout constraints log messages that you got when using the YouTube Helper Library.

If you take a closer look at the elements having Auto Layout constraints problems, you'll see AVAudioOnlyIndicatorView, AVUnsupportedContentIndicatorView, AVExternalPlaybackIndicatorView, etc. The constraints with warnings are not related to views you created but are related to Apple's internal views structure. It has nothing to do with the YouTube Helper Library or your implementation.

You should definitely file a report: https://bugreport.apple.com

These warnings won't get your app rejected or lessen your chance to get your app approved until the issue is fixed from Apple, especially if you can get the warnings using an empty project with a UIWebView loading any Youtube page.

HiDeoo
  • 10,353
  • 8
  • 47
  • 47