Close AVPlayer when movie is complete

RoryM picture RoryM · Oct 18, 2016 · Viewed 9.8k times · Source

I am making a simple iPad app to play a movie when a button is pressed. The movie plays and when the movie is finished I want to close AVPlayerView so it goes back to the main screen. Currently when the video finishes it stays on the last frame. My ViewController.Swift at the moment.

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
//MARK : Properties 

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
//MARK: Actions

@IBAction func playButton(_ sender: AnyObject) {

    let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mov")!
    let player = AVPlayer(url: movieURL as URL)

    let playerViewController = AVPlayerViewController()

    playerViewController.player = player

    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
        }
//    player.actionAtItemEnd = playerViewController.dismiss(animated: true)
}
}

As you can see, I think there might be something in actionAtItemEnd, but I'm not sure how to implement it. Thank you.

Answer

Dipak picture Dipak · Oct 19, 2016

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