My app has a start page and a second page with buttons that play videos. When a video is finished the AVPlayer is dismissed with playerItemDidReachEnd. But for some reason it shows the start page and not the second page when the player is dismissed. How can I get it to show the second page instead?
#import "ViewController.h"
@import AVKit;
@import AVFoundation;
@interface ViewController ()
@property(nonatomic, readonly) AVPlayerItem *currentItem;
@end
@implementation ViewController
AVPlayerViewController *playerViewController;
- (void)viewDidLoad {
[super viewDidLoad];
playerViewController = [[AVPlayerViewController alloc] init];
}
-(void)playerItemDidReachEnd:(NSNotification *) notification {
//remove the player
[self dismissViewControllerAnimated:NO completion:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (IBAction)playVideo:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVURLAsset *asset = [AVURLAsset assetWithURL: url];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: asset];
AVPlayer * player = [[AVPlayer alloc] initWithPlayerItem: item];
playerViewController.player = player;
UIScreen *mainScreen = [UIScreen mainScreen];
CGRect viewRect = mainScreen.bounds;
playerViewController.view.frame = viewRect;
playerViewController.showsPlaybackControls = YES;
[self.view addSubview:playerViewController.view];
[player play];
/* When the player item has played to its end time we'll dismiss the controller */
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:playerViewController.player.currentItem];
}
@end
If I understand your code correctly, your "second page" is ViewController
.
You are adding AVPlayerViewController
by [self.view addSubview:playerViewController.view];
, so you need to remove this view by calling
[playerViewController.view removeFromSuperview]
.
After [self dismissViewControllerAnimated:NO completion:nil];
, you dismiss whole ViewController
, not only AVPlayerViewController
.