Swift
This is a self contained project so that you can see everything in context.
Layout
Create a layout like the following with a UIView
and a UIButton
. The UIView
will be the container in which we will play our video.
Add a video to the project
If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).
Code
Here is the complete code for the project.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
Notes
- If you are going to be switching in and out different videos, you can use
AVPlayerItem
.
- If you are only using
AVFoundation
and AVPlayer
, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController
. You will need to import AVKit
for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.
MPMoviePlayerController
that you may have seen in other answers is deprecated.
Result
The project should look like this now.