How to detect when an AVPlayerItem is finished playing?
It uses NSNotification
to alert when playback is finished.
Register for the notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
Method to call when done:
-(void)itemDidFinishPlaying:(NSNotification *) notification {
// Will be called when AVPlayer finishes playing playerItem
}
Swift-i-fied (version 3)
class MyVideoPlayingViewController: AVPlayerViewController {
override func viewDidLoad() {
// Do any additional setup after loading the view.
super.viewDidLoad()
let videoURL = URL(fileURLWithPath: Bundle.main.path(forResource: "MyVideo",
ofType: "mp4")!)
player = AVPlayer(url: videoURL)
NotificationCenter.default.addObserver(self,
selector: #selector(MyVideoPlayingViewController.animationDidFinish(_:)),
name: .AVPlayerItemDidPlayToEndTime,
object: player?.currentItem)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
player?.play()
}
func animationDidFinish(_ notification: NSNotification) {
print("Animation did finish")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}