Reputation: 9493
Scenario: iOS device automatically plays a video via AVPlayer upon entering an AVPlayerViewController.
How do I detect when the AVPlayer has finished?
Upvotes: 0
Views: 3659
Reputation: 2872
Swift 4.0
NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
Upvotes: 0
Reputation: 650
Just in case it helps someone. And I know its in Obj-C, but I had to add this to some old code ;)
- (void)setupVideo {
NSString *stringVideoName = @"myVideo.mp4";
NSString *stringVideoPath = [[NSBundle mainBundle] pathForResource:stringVideoName ofType:nil];
NSURL *urlVideoFile = [NSURL fileURLWithPath:stringVideoPath];
_playerViewController = [[AVPlayerViewController alloc] init];
_playerViewController.player = [AVPlayer playerWithURL:urlVideoFile];
_playerViewController.view.frame = self.videoView.bounds;
_playerViewController.showsPlaybackControls = YES;
// Identify when the player time position jumps.
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playerItemTimeJumped:) name:AVPlayerItemTimeJumpedNotification object:_playerViewController.player.currentItem];
[self.videoView addSubview:_playerViewController.view];
self.videoView.autoresizesSubviews = YES;
}
- (void)playerItemTimeJumped:(NSNotification*)notification {
AVPlayerItem *playerItem = notification.object;
if (playerItem.status == AVPlayerItemStatusReadyToPlay) {
[NSNotificationCenter.defaultCenter removeObserver:self name:AVPlayerItemTimeJumpedNotification object:notification.object];
// The video play button has been pressed only once. Tell someone about it.
}
}
Upvotes: 1
Reputation: 5939
You can register to receive an AVPlayerItemDidPlayToEndTimeNotification
notification when a player item has completed playback.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.playerItem)
Upvotes: 1