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?
2
Answers
Unfortunately, no.
In
AVFoundation
, the notificationAVPlayerItemDidPlayToEndTime
is indeed the common and recommended way to detect when a video playback has reached its end.Overriding methods in
AVPlayer
orAVQueuePlayer
to detect the end of playback without using Key-Value Observing (KVO) or notifications isn’t supported directly by the API.you can build one for yourself:
You can go further and pass the action from outside like:
So you can add the action from the outside like:
⚠️ Don’t forget to remove observers when you done. For example you can do something like: