Search code examples
iosswiftmpmovieplayercontrollermpmovieplayer

MPMoviePlayerController Not Working - Swift


Ok so I have a view controller which I want to load a video file in MPMoviePlayerController on viewDidLoad. I am using the following code and when it runs, I get absolutely nothing. The code I am using is as follows:

import UIKit
import iAd
import MediaPlayer


class VideoPlayer: UIViewController {

    var moviePlayer : MPMoviePlayerController?


    func playVideo() {
        let url = NSURL (string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
        moviePlayer = MPMoviePlayerController(contentURL: url)
        if let player = moviePlayer {
            player.view.frame = self.view.bounds
            player.prepareToPlay()
            player.scalingMode = .AspectFill
            self.view.addSubview(player.view)
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()

playVideo()
    }
}

There is a segue from the mainViewController to the VideoPlayerViewController which is triggered when the play button is pressed. I know that the files are correctly linked as I have set up iAds in the file.

I will attach a few screenshots below: What I get when the simulator runs The Debug Console


Solution

  • Your problem is not in the code that you provided. it is somewhere else in your project. I just created a new singleView Project pasted your code. put playVideo in viewDidLoad. Run it and it is showing the video when the app starts.

    import UIKit
    import MediaPlayer
    
    class ViewController: UIViewController {
    
    var moviePlayer : MPMoviePlayerController?
    
    func playVideo() {
        let url = NSURL (string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
        moviePlayer = MPMoviePlayerController(contentURL: url)
        if let player = moviePlayer {
            player.view.frame = self.view.bounds
            player.prepareToPlay()
            player.scalingMode = .AspectFill
            self.view.addSubview(player.view)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        playVideo()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    }
    

    Adding a screenshot of a working app

    Screenshot