Close AVPlayer when movie is complete

This is working code in swift 5.3 and iOS 14.2, try this and let me know...:)

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
    
    let playerViewController = AVPlayerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func playButton(_ sender: AnyObject) {
        
        let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mp4")!
        let player = AVPlayer(url: movieURL as URL)
        
        playerViewController.player = player
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerViewController.player?.currentItem)
        
        self.present(playerViewController, animated: true) {
            self.playerViewController.player!.play()
        }
    }
    
    
    @objc func playerDidFinishPlaying(note: NSNotification) {
        self.playerViewController.dismiss(animated: true)
    }
}

You can download sample project for same from here https://github.com/deepakiosdev/AVPlayerViewControllerDemo


Using NSNotificationCenter you can do this .

 NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:  videoPlayer!.currentItem)

@objc func playerDidFinishPlaying(note: NSNotification) {
    // here you can do your dismiss controller logic
    AVPlayerViewController.dismiss(animated: true)
    print("Video Finished")
}

Swift 4

let playerController = AVPlayerViewController()

private func playVideo() {
    guard let path = Bundle.main.path(forResource: "p810", ofType:"mp4") else {
        debugPrint("video.m4v not found")
        return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))
    playerController.player = player
    NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)

    present(playerController, animated: true) {
        player.play()
    }
}

@objc func playerDidFinishPlaying(note: NSNotification) {
    playerController.dismiss(animated: true, completion: nil)
}