Leang Socheat
Leang Socheat

Reputation: 37

Swift, how to get event click done button during play the video on AVPlayer?

I have one TableViewController and I play video on that Table by tapping button inside cell to play by AVPlayer by code

@IBAction func btnFullScreen(sender: AnyObject) {    
    let playController = AVPlayerViewController()
    self.presentViewController(playController, animated: true, completion: nil)
    playController.player?.play()
}

So, It will play the video in full screen, and also exist with done button on the top left. I want to get event done button, after click the done button it will get the current time of player to do more something else. but how to get the event click done button?

Upvotes: 0

Views: 2724

Answers (2)

MohyG
MohyG

Reputation: 1348

I'm using this trick , it works on my scenario but it may give you a clue :

Step one:

add observers on a view controller you want to present your from there player view controller to get notified when its frame changes:

 self.playerViewController.addObserver(self, forKeyPath: #keyPath(MyViewController.view.frame), options: .new, context: nil)
 NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying),
                                               name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerViewController.player!.currentItem)

Step Two:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath ==  #keyPath(MyViewController.view.frame)){

        if playerViewController.player?.rate == 0{
            doneClicked()
        }
    }
}

Step Three:

    func doneClicked(){

    self.playerViewController.player!.pause()
    self.playerViewController.player!.rate =  0.0
    self.playerViewController.player = nil
    self.playerViewController.removeObserver(self, forKeyPath: #keyPath(HomeTabViewController.view.frame))
    NotificationCenter.default.removeObserver(self)
    self.playerViewController.dismiss(animated: false, completion: nil)
}

Upvotes: 0

Rajat
Rajat

Reputation: 11127

Currently, it is not possible that you can intercept the Done button of AVPlayerController, a Bug Report is submitted for this with radar: 27047358

You can only add an observer for AVPlayerItemDidPlayToEndTimeNotification which will be fired when your item finished playing.

Also according to the documentation:

Do not subclass AVPlayerViewController. Overriding this class’s methods is unsupported and results in undefined behaviour.

Reference - here

Upvotes: 1

Related Questions