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.
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?
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.
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.
To achieve what you are asking, you'll need to use AVPlayerLayer
Add a UIView outlet
@IBOutlet weak var videoView: UIView!
Import AVFoundation
Create player variables
var player : AVPlayer!
var avPlayerLayer : AVPlayerLayer!
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()
Add this method
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
avPlayerLayer.frame = videoView.layer.bounds
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With