Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Video Player in SwiftUI
Written by Team Kodeco

Playing videos is an essential component of a modern user interface. SwiftUI makes it easy to play videos by providing the VideoPlayer view. In this cookbook entry, you will learn how to create a basic video player in SwiftUI.

Note: If you want to try out the examples, you can download an archive of all the assets used in this section here.

To start, you need to import the AVKit framework in your project. This framework provides the necessary classes to play videos in SwiftUI. Next, add the following code to create and display a VideoPlayer view:

import AVKit

struct VideoPlayerView: View {
  // Create a URL for the video file in your app bundle
  let videoURL: URL? = Bundle.main.url(forResource: "BookTrailer", withExtension: "m4v")

  var body: some View {
    VStack {
      if let url = videoURL {
        VideoPlayer(player: AVPlayer(url: url))
      } else {
        Text("Video not found")
      }
    }
  }
}

struct ContentView: View {
  var body: some View {
    VideoPlayerView()
  }
}

Your preview should look like this:

Use VideoPlayer from AVKit to display a video player in your SwiftUI app.
Use VideoPlayer from AVKit to display a video player in your SwiftUI app.

Let’s break down the code:

  • struct VideoPlayerView: View declares a new SwiftUI View named VideoPlayerView.
  • let videoURL: URL? = Bundle.main.url(forResource: "BookTrailer", withExtension: "m4v") defines a URL for the video file in the app’s bundle. It attempts to locate a file named “BookTrailer.m4v” in the main app bundle.
  • var body: some View declares the main content of VideoPlayerView.
  • if let url = videoURL { VideoPlayer(player: AVPlayer(url: url)) } else { Text("Video not found") } checks if the videoURL has been set. If the video file was found, a VideoPlayer view is created that plays the video at the given URL. If not, a Text view is created that displays the message “Video not found”.
  • struct ContentView: View { var body: some View { VideoPlayerView() } } declares a new SwiftUI View named ContentView which displays the VideoPlayerView when it’s shown.

Creating a video player in SwiftUI is as simple as creating a VideoPlayer view and adding an AVPlayer object with the URL of the video to play. You can further customize the video player by modifying the properties of the AVPlayer object.

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.