Implementing Video Streaming in SwiftUI
Written by Team Kodeco
Video streaming is an integral part of many modern apps, and it’s important for SwiftUI developers to understand how to implement this functionality. In SwiftUI, it’s surprisingly straightforward to incorporate video streaming into your app. You can achieve this with just a few lines of code.
In this example, you’ll leverage SwiftUI’s VideoPlayer
view, which simplifies the process of streaming videos from remote URLs. The VideoPlayer
view wraps around AVPlayerViewController
, providing a full-fledged video player interface with playback controls.
Here’s how you can use VideoPlayer in your SwiftUI app:
import AVKit
struct ContentView: View {
var body: some View {
NavigationStack {
VideoPlayer(player: AVPlayer(url: URL(string: "https://archive.org/download/four_days_of_gemini_4/four_days_of_gemini_4_512kb.mp4")!))
.navigationTitle("Video Player")
}
}
}
Your preview should look like this:
Here’s how this code works:
-
The
AVKit
module is imported. This module includes theVideoPlayer
view, as well asAVPlayer
, which is responsible for managing and controlling the playback of audiovisual media. -
In the
ContentView
struct, aNavigationStack
is created to contain the VideoPlayer. -
Inside the
NavigationStack
, aVideoPlayer
view is initialized with anAVPlayer
instance, which is in turn initialized with a URL that points to the video to stream.
You’ve added a title to the navigation view using the .navigationTitle
modifier.
That’s all there is to it! With the introduction of VideoPlayer
view in SwiftUI, it’s never been easier to stream videos from remote URLs. VideoPlayer
provides a full-fledged video player interface out of the box, so you can focus on building your app’s functionality. However, if you need more control over the video player, AVPlayer
and AVPlayerViewController
provide additional APIs for customization.