Adalex3
Adalex3

Reputation: 420

How to add a video in the UI in Swift

I want to be able to add a video (called "Logo-Animation4.mp4") into the UI in Swift, just like you can a UIImage in a UIImageView.

UIImageView

Right now, I've tried just putting an AVPlayer on the view, but it comes up with the default iOS AVPlayer, which contains the regular fullscreen, controls, and volume stuff that I don't want. I just want the video to play in the UI without any way to have the user interact with it.

I've thought about animating the video using a regular UIImageView's animation feature, but my video isn't that short, and it would be hard to get every single frame, and input it into the code.

How should I go about doing this?

Upvotes: 6

Views: 5675

Answers (1)

Aryan Sharma
Aryan Sharma

Reputation: 635

To achieve what you are asking, you'll need to use AVPlayerLayer

  1. Add a UIView outlet

    @IBOutlet weak var videoView: UIView!
    
  2. Import AVFoundation

  3. Create player variables

    var player : AVPlayer!
    var avPlayerLayer : AVPlayerLayer!
    
  4. Add the following code to your viewDidLoad

    guard let path = Bundle.main.path(forResource: "Logo-Animation4", ofType:"mp4") else {
        debugPrint("Logo-Animation4.mp4 not found")
        return
    }
    player = AVPlayer(url: URL(fileURLWithPath: path))
    avPlayerLayer = AVPlayerLayer(player: player)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resize
    
    videoView.layer.addSublayer(avPlayerLayer)
    player.play()
    
  5. Add this method

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        avPlayerLayer.frame = videoView.layer.bounds
    }
    

Upvotes: 6

Related Questions