Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Use a VideoPlayer view to stream video.
Use a VideoPlayer view to stream video.

Here’s how this code works:

  • The AVKit module is imported. This module includes the VideoPlayer view, as well as AVPlayer, which is responsible for managing and controlling the playback of audiovisual media.

  • In the ContentView struct, a NavigationStack is created to contain the VideoPlayer.

  • Inside the NavigationStack, a VideoPlayer view is initialized with an AVPlayer 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.