Incorporating Videos in SwiftUI using VideoPlayer
Let’s learn how to embed videos in your SwiftUI applications using the VideoPlayer
view from AVKit
. This view provides the necessary tools to play and control videos.
Let’s take a look at a practical example:
import AVKit
import SwiftUI
struct CustomVideoPlayer: View {
var body: some View {
// 1
if let url = Bundle.main.url(forResource: "my-video", withExtension: "mp4") {
// 2
VideoPlayer(player: AVPlayer(url: url))
// 3
.frame(width: 300, height: 200)
} else {
Text("No video")
}
}
}
Let’s briefly analyze this code:
- We obtain the location of the video, which is part of our project, and store it in the variable
url
. - We create an instance of
VideoPlayer
using anAVPlayer
configured with the obtained URL. - We customize the size of the player using the
frame
modifier. If you want it to take up the entire screen, you can replace.frame(width: 300, height: 200)
with.ignoresSafeArea()
.
In this example, we use Bundle.main.url(forResource:withExtension:)
to get the URL of the video. However, you can also play videos hosted on external servers as follows:
VideoPlayer(player: AVPlayer(url: URL(string: "<video url>")!))
Adding an Overlay
If you want to overlay elements on the video, you can use another constructor of VideoPlayer
:
init(player: AVPlayer?, @ViewBuilder videoOverlay: () -> VideoOverlay)
This constructor allows you to add custom content over the video. Let’s see an example:
VideoPlayer(player: AVPlayer(url: url)) {
HStack {
Spacer()
Image(systemName: "video.bubble.left.fill")
.foregroundColor(.green)
.padding()
}
}
In this code, in addition to the video URL, we pass a closure. This closure contains an HStack
with an SF Symbol with the color green
and a Spacer
to position it on the right.
Here’s how it would look:
You can place any custom view and use all the available space according to your needs.
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/reproducir-video-en-swiftui/