MPMovieController won't dismiss on Done button

609 views Asked by At

My movie file starts no problem. The done button does not dismiss the video content. No idea why? Also, Fast Forward and Rewind buttons just cause a black screen. I don't think I am using the notification functions correctly?

import Foundation
import UIKit
import MediaPlayer

class VideoViewController: UIViewController {

var moviePlayer:MPMoviePlayerController!

@IBAction func videoLaunch(sender: AnyObject) {
    playVideo()
}
func playVideo() {
let path = NSBundle.mainBundle().pathForResource("MyVideo", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer {
player.view.frame = self.view.bounds
moviePlayer?.controlStyle = MPMovieControlStyle.Fullscreen
player.prepareToPlay()
self.view.addSubview(player.view)

}
}


override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "moviePlayBackDidFinish:",
        name: MPMoviePlayerPlaybackDidFinishNotification,
        object: moviePlayer)


    func moviePlayBackDidFinish(notification: NSNotification){
        self.view.removeFromSuperview()
    }



    }
}
2

There are 2 answers

3
f3n1kc On BEST ANSWER

You are adding player view as subview. You should remove it (removeFromSuperview) after done button pressed. Use notifications to listen for playback finish:

NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "moviePlayBackDidFinish:",
name: MPMoviePlayerPlaybackDidFinishNotification,
object: moviePlayer)

and moviePlayBackDidFinish:

func moviePlayBackDidFinish(notification: NSNotification){
  // remove from superview
}
0
Roman Barzyczak On

You should remove moviePlayer from your superview like this:

   func moviePlayBackDidFinish(notification: NSNotification){
        let moviePlayer:MPMoviePlayerController = notif.object as! MPMoviePlayerController

    moviePlayer.view.removeFromSuperview()
}

Because in your case you remove self.view