Search code examples
iosswiftavplayertvos

When subclassing AVPlayer, is there a more direct way to know when a player item ends, than using notification center?


When using AVPlayer,

the only way I know to detect the end of a video being reached,

is to use the notification, just as you would when detecting the end of a video from the view controller. Eg,

class FancyAVPlayer: AVQueuePlayer {
    
    override init() {
        super.init()
        NotificationCenter.default.addObserver(self,
           selector: #selector(innerEnd),
           name: .AVPlayerItemDidPlayToEndTime, object: nil)
    }
    
    @objc func innerEnd() {
        print("AVPlayer subclass, tape ended")
    }

    override func insert ..etc
    override func remove ..etc
}

I have always wondered, there must be a more sensible way to do this, by overriding something in AVPlayer.

Has anyone solved this issue?


Solution

  • Unfortunately, no.

    In AVFoundation, the notification AVPlayerItemDidPlayToEndTime is indeed the common and recommended way to detect when a video playback has reached its end.

    Overriding methods in AVPlayer or AVQueuePlayer to detect the end of playback without using Key-Value Observing (KVO) or notifications isn't supported directly by the API.