SwiftUI Blog

Mastering SwiftUI: Your Guide to Building Beautiful, Intuitive Apps.

Play a video

A nice feature that an iOS application can have is a video player. It’s simple to build.

There are two ways to play a video:

  • Embed it in the application
  • Stream it from a remote source (not YouTube — for that, there’s another post)

Video Embedded

First of all, we need a video, i downloaded this one bird, renamed it to bird.mp4 and
and copied it into the project (not into the assets folder).

Now take a look at the code:

import SwiftUI
import AVKit

struct ContentView: View {
    @State var player = AVPlayer(
        url: Bundle.main.url(
            forResource: "bird", withExtension: "mp4")!,
        
        ) 
    var body: some View {
        VStack {
            VideoPlayer(player: player)
                .frame(width: 320, height: 240)
            HStack(spacing: 20) {
                Button(action: {player.pause()}) {
                    Label("Pause", systemImage: "pause.rectangle.fill")
                }
                Button(action: {player.play()}) {
                    Label("Play", systemImage: "play.square.fill")
                }
                Button(action: {
                    player.pause()
                    player.seek(to: .zero)
                }) {
                    Label("Stop", systemImage: "stop.fill")
                }
                
            }
        }.padding()
    }
}

First, we need to import AVKit (Audio Video Kit), then declare the player as a state variable (because the player’s state can change). The player requires a URL pointing to the video. In this case, we provide the name and format of the file.

The behavior of the buttons is mostly self-explanatory. The only one that requires a bit more explanation is the Stop button. In its action, we pause the player and use seek to jump back to the beginning of the video.

Remote video

If we want to play a remote video, the only thing we need to do is change the URL in the video player, like this:

@State var player = AVPlayer(
        url: URL(string: "https://example.com/bird.mp4")!) 

As an exercise, you can try using a single button that toggles both the icon and the action, depending on the player’s state.