Search code examples
iphonexcodevideoswiftmpmovieplayercontroller

How can I play an intro video the first time I launch an iPhone app using swift (NOT objective-c)?


I want to play an intro video for my iPhone app the first time it launches. I have it set up to detect that it's the first launch, but how do I play the video from the app (not a url) using SWIFT? Do I set it up in the first ViewController file or in the AppDelegate? I've tried using MPMoviePlayerController, but I just can't seem to get it to actually play. Thank you for your help!


Solution

  • I had this same trouble. Here's my solution:

    func playVideo() {
            let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4")
            let url = NSURL.fileURLWithPath(path!)
            moviePlayer = MPMoviePlayerController(contentURL: url)
            if let player = moviePlayer {
                player.view.frame = self.view.bounds
                player.controlStyle = .None
                player.prepareToPlay()
                player.scalingMode = .AspectFit
                self.view.addSubview(player.view)
            }
        }
    

    Don't forget to import MediaPlayer and declare your variable - var moviePlayer: MPMoviePlayerController?

    Then call your function when you want to play it playVideo()

    See my question for how to dismiss it - In iOS how do I programmatically add a video view and then remove it after it finishes playing using Swift? I got a really helpful answer there.

    Also notice that I disabled my controllers because I don't want it to be seen.