21

I've been looking through the AVPlayerItem and AVPlayer docs and there doesn't seem to be any callbacks for when the item is finished playing. I was hoping that there would be some sort of delegate callback that we can utilize or that AVPlayerActionAtItemEnd would provide a custom action for us to write.

How can i figure out a way to detect when AVPlayer has finished playing an item?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
3254523
  • 3,016
  • 7
  • 29
  • 43

3 Answers3

45

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
}
random
  • 8,568
  • 12
  • 50
  • 85
7

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)
    }

}
jhelzer
  • 295
  • 2
  • 12
  • Good answer but be sure to invoke removeObserver(_:name:object:) before observer or any object specified in addObserver:selector:name:object: is deallocated. – pierre23 Oct 12 '16 at 23:58
0

This is how I did it.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinishedCallback:) name:AVPlayerItemDidPlayToEndTimeNotification object:player.currentItem];


- (void)movieFinishedCallback:(NSNotification*)aNotification
{
   // [self dismissViewControllerAnimated:YES completion:Nil];
}
nithinreddy
  • 6,167
  • 4
  • 38
  • 44