Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayerItemDidPlayToEndTimeNotification not firing

I am playing video from the url using AVPlayer. AVPlayerItemDidPlayToEndTimeNotification is not firing. I have put the breakpoints to check. Below is my code snippet:-

    @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)
}
like image 726
Keshav Raj Avatar asked Nov 23 '15 12:11

Keshav Raj


Video Answer


3 Answers

According to the docs, the observed object must be the AVPlayerItem instance, not the AVPlayer itself. Try changing self.moviePlayer to self.moviePlayer.currentItem.

like image 125
davidgoli Avatar answered Sep 28 '22 14:09

davidgoli


the property actionAtItemEnd of AVPlayer is KVO compliant:

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

like image 30
kholl Avatar answered Sep 28 '22 16:09

kholl


This works for me:

NotificationCenter.default.addObserver(self, 
selector:#selector(didEndPlayback), 
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:nil)
like image 36
atulkhatri Avatar answered Sep 28 '22 14:09

atulkhatri