How to use Swift to detect when AVPlayer video ends playing?

To detect the end of a video in swift we’ll need to create a video player, then use notifications to detect when the video stops playing. We’ll do this with help of an example in swift.

Let’s create a project and drag and drop any video with extension “mp4”, select copy resource if required and add to the target of our project.

Now we’ll programmatically first create a Video Player, then we’ll create url of the video in our project, and then we’ll play the video.

var videoPlayer: AVPlayer!

Now, in the viewDidAppear add the following code.

override func viewDidAppear(_ animated: Bool) {
   let filepath: String? = Bundle.main.path(forResource: "Introduction", ofType: "mp4")
   if let videoPath = filepath {
      let url = URL.init(fileURLWithPath: videoPath)
      videoPlayer = AVPlayer(url: url)
      let playerLayer = AVPlayerLayer(player: videoPlayer)
      playerLayer.frame = self.view.bounds

The above code will create a video player, and add it as a sublayer to our default view in the view controller.

Now we need to add an observer to our player, and also create an observer method that should be called when it detects the end of the video. Add the code block below to the viewDidAppear method.

NotificationCenter.default.addObserver(self, selector: #selector(videoDidEnd), name:
NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

Now we need to write the videoDidEnd method too, Inside this method you can perform any action you want, for now, we’ll just print “video ended” when the video ends and the notification center calls this method.

@objc func videoDidEnd(notification: NSNotification) {
   print("video ended")

When we run this code we get the following result.

Once the video stops playing we get output in our console.

Now, the above code does the required thing for us, but for efficient memory usage, we also need to remove the observer, which can be done using the code below.

deinit {
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know