Youtube API in IOS 7 and IOS 8

I have these requirements to play youtube video in my application:

  • Autoplay when displaying a container.
  • Detect when video ends (enabling controls in this case)
  • It does not start in full screen mode
  • Support for full screen portrait and landscape
  • Fully compatible with IOS 7 and 8

First, I'll try to help you with the youtube-ios-player-helper:

  • IOS 8: work perfect.
  • IOS 7: Video pause every time in full screen and no liquid is played.

I believe this might be the best solution, but I cannot get it to work fine on IOS 7.

Second and actual option, I am using a hybrid solution: IOS 8 with youtube-ios-player-helper and IOS 7 with UIWebView and built-in YouTube player. Result:

  • IOS 8: work perfect.
  • IOS 7: work, but 1/5 video autoplay doesn't work, so no video completion detected (I don't know why)

I appreciate any suggestion for a better solution,

My actual code (second option):

-(void)youtubePlayerConfiguration{

NSString *version = [[UIDevice currentDevice] systemVersion];


if ([version floatValue] >= 8.0) {

    NSDictionary *playerVars = @{

                                 @"playsinline" : @1,
                                 @"autoplay" : @1,
                                 @"showinfo" : @0,
                                 @"autohide" : @1,
                                 @"rel" : @0,
                                 @"modestbranding" : @1
                                 };

     youtubePlayer.delegate = self;
     [youtubePlayer loadWithVideoId:self.videoId playerVars:playerVars];

} else {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:youtubePlayer.frame];
    [webView setAllowsInlineMediaPlayback:YES];
    [webView setMediaPlaybackRequiresUserAction:NO];
    webView.delegate = self;

    [self.view addSubview:webView];

    NSString* embedHTML = [NSString stringWithFormat:@"\
                           <html>\
                           <body style='margin:0px;padding:0px;'>\
                           <script type='text/javascript' src='http://www.youtube.com/iframe_api'></script>\
                           <script type='text/javascript'>\
                           function onYouTubeIframeAPIReady()\
                           {\
                           ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady,onStateChange: onPlayerStateChange}})\
                           }\
                           function onPlayerReady(a)\
                           { \
                           a.target.playVideo(); \
                           }\
                           var done = false;\
                           function onPlayerStateChange(event) {\
                               if (event.data == YT.PlayerState.PLAYING && !done) {\
                                   setTimeout(stopVideo, 6000);\
                                   done = true;\
                               }\
                               if (event.data == YT.PlayerState.ENDED) {\
                                   window.location = 'callback:anything';\
                               }\
                           }\
                           </script>\
                           <iframe id='playerId' type='text/html' width='%d' height='%d' src='http://www.youtube.com/embed/%@?enablejsapi=1&rel=0&playsinline=1&autoplay=1&showinfo=0' frameborder='0'>\
                           </body>\
                           </html>", 288,150, self.videoId];
    [webView loadHTMLString:embedHTML baseURL:[[NSBundle mainBundle] resourceURL]];

    webView.allowsInlineMediaPlayback = YES;
    webView.mediaPlaybackRequiresUserAction = NO;
    webView.scrollView.bounces = NO;

    youtubePlayer.hidden = YES;
}

}


#pragma mark - Player YouTube Delegates

-(void)playerViewDidBecomeReady:(YTPlayerView *)playerView{
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"Playback started" object:self];

    [playerView playVideo];
}

- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state{
    if (state == kYTPlayerStateEnded) {
        ratingView.editable = YES;
        ratingView.alpha = 1;
        ratingView.userInteractionEnabled = YES;
    }
}

- (void)playerView:(YTPlayerView *)playerView receivedError:(YTPlayerError)error
{
    NSLog(@"YTPlayerView : receivedError :%i",error);
}

#pragma mark - WebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"ENTRO - request:%@",request);

    if ( [[[request URL] scheme] isEqualToString:@"callback"] ) {

        NSLog(@"get callback");
        ratingView.editable = YES;
        ratingView.alpha = 1;
        ratingView.userInteractionEnabled = YES;
        return NO;

    }

    return YES;
}

      

+3


source to share


1 answer


I used the following code for iOS 7 and it worked fine for me, now I am using iOS 8, so I am using youtube-ios-player-helper .



-(void)initializeYouTubePlayerWithVideoID(NSString *)videoId
{
    NSString *youTubeVideoHTML = @"<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:'1024', height:'728', videoId:'%@', playerVars: {controls:0,rel:0, modestbranding:1, html5:0, showinfo:0}, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } function onPlayerReady(event) { event.target.playVideo(); } function onPlayerStateChange(event) { if (event.data == YT.PlayerState.ENDED){ } } </script> </body> </html>";

    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];

    _youtubePlayerView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
    _youtubePlayerView.backgroundColor = [UIColor blackColor];
    _youtubePlayerView.delegate = self;
    _youtubePlayerView.allowsInlineMediaPlayback = NO;

    [self.view addSubview:_youtubePlayerView];

    _youtubePlayerView.mediaPlaybackRequiresUserAction = NO;
    [_youtubePlayerView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playerDidExitFullscreen:)
                                             name:@"UIMoviePlayerControllerDidExitFullscreenNotification"
                                           object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playerDidEnterFullscreen:)
                                                 name:@"UIMoviePlayerControllerDidEnterFullscreenNotification"
                                           object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackStateDidChange:)
                                             name:@"MPAVControllerPlaybackStateChangedNotification"
                                           object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackDidEnd:)
                                             name:@"MPAVControllerItemPlaybackDidEndNotification"
                                           object:nil];
}

-(void)playbackStateDidChange:(NSNotification *)notification
{
    switch ([[notification.userInfo objectForKey:@"MPAVControllerNewStateParameter"]     intValue])
   {
        case 0:
            //Loading
            break;
        case 1:
            //Paused

            break;
        case 2:
            //Playing";
            break;
        case 3:
           //Buffering";
        break;

        default:
            break;
    }
}

-(void)playbackDidEnd:(NSNotification *)notification
{
    //Playback Ended
}

-(void)playerDidExitFullscreen:(NSNotification *)notification
{
     //playerDidExitFullscreen 
}

-(void)playerDidEnterFullscreen:(NSNotification *)notification
{
    //playerDidEnterFullscreen
}

      

+2


source







All Articles