Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to play a YouTube video on iOS without revealing/adding a view, while still following YouTube's Terms of Service?

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?

like image 846
Doug Smith Avatar asked Nov 06 '14 03:11

Doug Smith


3 Answers

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.

like image 69
Suraj Pathak Avatar answered Oct 19 '22 22:10

Suraj Pathak


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.

like image 25
Zhang Avatar answered Oct 19 '22 23:10

Zhang


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.

like image 39
HiDeo Avatar answered Oct 20 '22 00:10

HiDeo