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)
}
According to the docs, the observed object must be the AVPlayerItem
instance, not the AVPlayer
itself. Try changing self.moviePlayer
to self.moviePlayer.currentItem
.
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
This works for me:
NotificationCenter.default.addObserver(self,
selector:#selector(didEndPlayback),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With