Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close Video Player Subview if video played Swift iOS

I try to let my Video player close after the video is played.

 func playVideoPepper() {

        var maxVideoCount:Int =  5 //AnzahlderVideos
        var Random = Int(arc4random_uniform(maxVideoCount + 0))
        var VideoNumber = Random + 1


        let path = NSBundle.mainBundle().pathForResource("pepper\(VideoNumber)", ofType:"mp4")
        let url = NSURL.fileURLWithPath(path!)
        moviePlayer = MPMoviePlayerController(contentURL: url)
        if let player = moviePlayer {
            player.view.frame = self.view.bounds
            player.prepareToPlay()
            player.scalingMode = .AspectFill
            player.controlStyle = .None
            self.view.addSubview(player.view)
            var time = player.duration
            println(time)
        }

    }

I tried to get the time how long one of the videos (random on of 5 videos is played) with .duration or .playableduration but both give me a 0.00 is there any easy way to let the SubView be removed if the video is played?

like image 963
Fabian Boulegue Avatar asked Feb 11 '23 02:02

Fabian Boulegue


1 Answers

You need to subscribe to MPMoviePlayerPlaybackDidFinishNotification, of the MPMoviePlayerController. This notification is posted when the player finished playing the video.

You can add the controller as an observer in the viewWillAppear method:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerDidFinish:"), name: MPMoviePlayerPlaybackDidFinishNotification, object: player)

Don't forget to remove the controller from the notification center this is ussualy done in viewWillDisappear method:

NSNotificationCenter.defaultCenter().removeObserver(self)

See docs of MPMoviePlayerController here

like image 111
Marius Fanu Avatar answered Feb 13 '23 21:02

Marius Fanu