AVPlayerItemDidPlayToEndTimeNotification not working

I am playing video from a URL using AVPlayer. AVPlayerItemDidPlayToEndTimeNotification does not start. I set breakpoints for verification. Below is a snippet of code: -

@IBAction func playButtonClicked(sender: UIButton) { let url:NSURL = NSURL(string: self.currentSelectedContent.link)! moviePlayer = AVPlayer(URL: url) playerViewController = AVPlayerViewController() playerViewController.player = moviePlayer self.presentViewController(playerViewController, animated: true) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayBackFinished", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.moviePlayer) self.playerViewController.player?.play() } } func moviePlayBackFinished() { self.playerViewController.dismissViewControllerAnimated(true, completion: nil) } 
+7
ios swift avplayer avplayerviewcontroller
source share
3 answers

According to the docs, the observed object should be an instance of AVPlayerItem , not AVPlayer . Try changing self.moviePlayer to self.moviePlayer.currentItem .

+17
source share

the actionAtItemEnd property of AVPlayer complies with KVO requirements:

 moviePlayer.addObserver(self, forKeyPath: "actionAtItemEnd", options: [], context: nil) override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "actionAtItemEnd"{ // print("FINISH") } } 

https://developer.apple.com/documentation/avfoundation/avplayer/1387376-actionatitemend

https://developer.apple.com/documentation/avfoundation/avplayeractionatitemend

+5
source share

This works for me:

 NotificationCenter.default.addObserver(self, selector:#selector(didEndPlayback), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:nil) 
+2
source share

All Articles