iosxcodeswiftmpmoviewcontroller

MPMovieController won't dismiss on Done button


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()
    }



    }
}

Solution

  • 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
    }