0Pricing
Swift Academy · Lesson

Embedding Players in SwiftUI

Use VideoPlayer and custom player views.

Embedding Players in SwiftUI is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “Embedding Players in SwiftUI” lesson free?

Yes — the full text of “Embedding Players in SwiftUI” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

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