Search code examples
iosobjective-ciphonesegueavplayerviewcontroller

AVPlayer to fullscreen without black bars on top and bottom


I have embedded my video and added a notificationCenter observer as shown below:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"export" ofType:@"mp4"];
NSURL *videoURL = [NSURL fileURLWithPath:filePath];

_playerViewController = [[AVPlayerViewController alloc] init];
// grab a local URL to our video
//NSURL *videoURL = [myBundle URLForResource:@"export" withExtension:@"mp4"];
NSLog(@"Video URL: %@",videoURL);
if(videoURL)
{

    _playerViewController.showsPlaybackControls = NO;

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:videoURL];

    // create an AVPlayer
    _playerViewController.player = [AVPlayer playerWithPlayerItem:playerItem];
   //self.player.volume = PLAYER_VOLUME;
   _playerViewController.modalPresentationStyle = 
   UIModalPresentationOverFullScreen;
   AVPlayerLayer *playerLayer = [AVPlayerLayer 
     playerLayerWithPlayer:_playerViewController.player];
   playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    playerLayer.zPosition = -1;
   playerLayer.frame = [UIApplication sharedApplication].keyWindow.bounds;
   [self.playerView.layer addSublayer:playerLayer];

   [_playerViewController.player play];
   // Adding Observer for your video file,
  NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  [notificationCenter addObserver:self selector:@selector(videoDidFinish:) 
  name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

When the video is finished playing, the following method is called:

 -(void)videoDidFinish:(id)notification{
     AVPlayerItem *p = [notification object];
     //do something with player if you want
     [_playerViewController.player pause];

     //Remove Observer
     [[NSNotificationCenter defaultCenter] removeObserver:self];

      //your initial view can proceed from here
     UIViewController *controler = [self.storyboard 
    instantiateViewControllerWithIdentifier:@"loginScreenId"];
   [self.navigationController pushViewController:controler animated:YES];
}

I'm unable to fix two things:

  1. I'm pushing from current AV view controller to next view controller. It's successfully segued to next view controller but the screen have top and bottom black bars. How can I get rid of this?
  2. How can I make the AVPlayer fullscreen?

Solution

  • Finally, I figured it out. I just added Launch.storyborad to the project and replaced the code

    playerLayer.frame = [UIApplication sharedApplication].keyWindow.bounds;
    

    with

    playerLayer.frame = self.view.frame;
    

    to get fullscreen Video.