Recently I needed to add a video as a background in one of my apps. This is a really nice effect if it’s a looping video. On top of the video I had some other elements and buttons, it was cool to see motion happening behind. The code snippet below displays the video full screen with no controls and it repeats, but you could change the properties to suit your needs.
- First add the video to your project, just like any file, you can drag it into your Project Navigator or right click in the Project Navigator and select “Add Files”. Be sure to choose the targets that you need to add the file to, if you have more than one.
- In the Project Navigator select your Project Root > Your Target > Build Phases > Copy Bundle Resources. Check to see that you video is there, if not click the plus sign to add it.
- Add this import statement to the top of your View Controller.
import MediaPlayer
- Add this property to your class.
var moviePlayer : MPMoviePlayerController!
- Add the code below to create and play your video. This can be added to your ViewDidLoad() method or create your own function.
let path = NSBundle.mainBundle().pathForResource("Video", ofType:"mp4") let url = NSURL.fileURLWithPath(path!) self.moviePlayer = MPMoviePlayerController(contentURL: url) if let player = self.moviePlayer { player.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) player.view.sizeToFit() player.scalingMode = MPMovieScalingMode.Fill player.fullscreen = true player.controlStyle = MPMovieControlStyle.None player.movieSourceType = MPMovieSourceType.File player.repeatMode = MPMovieRepeatMode.One player.play() self.view.addSubview(player.view) }