Swift Academy · Lesson

Embedding Players in SwiftUI

Use VideoPlayer and custom player views.

Lesson 4 of 413 steps

Embedding Players in SwiftUI is a free Swift Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

Video in SwiftUI

SwiftUI provides the VideoPlayer view (from AVKit) to embed media playback declaratively, with built-in controls.

import SwiftUI
import AVKit

The VideoPlayer View

VideoPlayer takes an AVPlayer and renders it with standard transport controls—play, pause, scrubber, fullscreen.

struct PlayerScreen: View {
    let player = AVPlayer(url: URL(string: "https://example.com/v.mp4")!)
    var body: some View {
        VideoPlayer(player: player)
            .frame(height: 240)
    }
}

Holding the Player in State

Store the AVPlayer in @State so it survives view updates. Recreating it every body call would restart playback.

struct PlayerScreen: View {
    @State private var player = AVPlayer(
        url: URL(string: "https://example.com/v.mp4")!)
    var body: some View {
        VideoPlayer(player: player)
    }
}

Controlling Playback

Drive playback from SwiftUI lifecycle modifiers: start on appear, pause on disappear, to avoid audio continuing off-screen.

VideoPlayer(player: player)
    .onAppear { player.play() }
    .onDisappear { player.pause() }

Overlay Content

The VideoPlayer initializer accepts an overlay closure for custom UI layered above the video—titles, badges, captions.

VideoPlayer(player: player) {
    VStack {
        Spacer()
        Text("Live")
            .padding(6)
            .background(.red, in: Capsule())
    }
}

Looping Playback

Loop by observing the end-of-item notification and seeking back to zero. An AVPlayerLooper with a queue player is another option.

.onAppear {
    NotificationCenter.default.addObserver(
        forName: .AVPlayerItemDidPlayToEndTime,
        object: player.currentItem, queue: .main) { _ in
        player.seek(to: .zero); player.play()
    }
}

Audio Session for Video

Configure an AVAudioSession so video audio behaves correctly—respecting the mute switch or playing through it as desired.

try? AVAudioSession.sharedInstance().setCategory(.playback)

Custom Players with UIViewRepresentable

When you need a fully custom UI (no system controls), wrap an AVPlayerLayer in a UIViewRepresentable instead of using VideoPlayer.

struct PlayerLayerView: UIViewRepresentable {
    let player: AVPlayer
    func makeUIView(context: Context) -> UIView { PlayerUIView(player: player) }
    func updateUIView(_ uiView: UIView, context: Context) { }
}

The Backing UIView

The custom UIView hosts an AVPlayerLayer and resizes it to its bounds, giving you a controls-free video surface.

final class PlayerUIView: UIView {
    init(player: AVPlayer) {
        super.init(frame: .zero)
        let layer = AVPlayerLayer(player: player)
        layer.videoGravity = .resizeAspectFill
        self.layer.addSublayer(layer)
    }
    required init?(coder: NSCoder) { fatalError() }
}

Picture in Picture

For Picture in Picture, use AVPictureInPictureController with your player layer and enable the background audio capability.

let pip = AVPictureInPictureController(playerLayer: playerLayer)
pip?.startPictureInPicture()

Cleaning Up

Pause the player and remove observers when the view disappears to free resources and stop background audio you did not intend.

.onDisappear {
    player.pause()
    // remove notification observers here
}

Quick Check: SwiftUI Players

Test your understanding of embedding players in SwiftUI.

Recap: Embedding Players in SwiftUI

AVKit’s VideoPlayer embeds an AVPlayer with standard controls; keep the player in @State for a stable instance and drive play/pause from onAppear/onDisappear. Add overlays via the trailing closure and loop on the end notification.

For custom, controls-free playback, wrap an AVPlayerLayer in a UIViewRepresentable, and clean up observers on disappear.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Embedding Players in SwiftUI” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Embedding Players in SwiftUI”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Embedding Players in SwiftUI”?

Use VideoPlayer and custom player views. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Embedding Players in SwiftUI” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Playing Media with AVPlayer
  2. Recording Audio
  3. AVAsset and Composition
  4. Embedding Players in SwiftUI
← Back to Swift Academy