Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 705
Adalex3 Avatar asked Feb 24 '18 16:02

Adalex3


People also ask

How do I make a video player in SwiftUI?

Getting Started. As per the official documentation, adding a video player to a SwiftUI app is pretty simple. Import AVKit and add a VideoPlayer view to your own View, with an AVPlayer argument, and we can create one just like this.

How do I embed a YouTube video in SwiftUI?

WebViews in SwiftUI Just replace the URL in the WebViewModel init with your YouTubeURL and that's it, you have a YouTube video embedded in the app. Now, if you want to open the YouTube video in full screen, just replace the occurrences of watch? for watch_popup? as follow: return url.


1 Answers

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
    }
    
like image 186
Aryan Sharma Avatar answered Nov 08 '22 13:11

Aryan Sharma