1. Guides
  2. Guide

Looping video in SwiftUI, without a gap.

One small view, one looper, and no gap at the join.

To loop video in SwiftUI, wrap a UIView whose layer is an AVPlayerLayer in a UIViewRepresentable, give it an AVQueuePlayer and hand both the player and the clip to an AVPlayerLooper. Keep the looper in the view’s coordinator, because the loop stops once it is freed. Mute the player, pause it when the view leaves the screen or the scene stops being active, and keep the layer clear so transparent HEVC clips show what is behind them.

Updated

The bench press, back squat and deadlift, three lifts a training app starts with, each a square loop like the ones this guide plays. Each clip opens its lift’s page.

Why VideoPlayer won’t do

AVKit’s VideoPlayer is, in Apple’s words, "A view that displays content from a player and a native user interface to control playback." That native interface is the trouble for a demo clip: a tap brings up playback controls, and SwiftUI has no modifier to switch them off.

VideoPlayer also keeps its layer to itself, so you cannot set the video gravity or a clear background. A small UIViewRepresentable gives you all three in about sixty lines.

Loop video in SwiftUI: the view

The UIView uses AVPlayerLayer as its own layer class, the pattern Apple’s AVPlayerLayer page shows, so the video follows the view’s size with no layoutSubviews. A small LoopingPlayer class owns the AVQueuePlayer and the AVPlayerLooper, and SwiftUI keeps it as the coordinator for as long as the view exists.

updateUIView loads the URL and plays or pauses, so the parent drives playback with a plain Bool. The code builds against the iOS 17 SDK and later in both Swift 5 and Swift 6 language modes.

import AVFoundation
import SwiftUI
import UIKit

/// A UIView whose own layer is an AVPlayerLayer, so the video resizes with the view.
final class PlayerLayerView: UIView {
    override static var layerClass: AnyClass { AVPlayerLayer.self }
    var playerLayer: AVPlayerLayer { layer as! AVPlayerLayer }
}

/// Owns the queue player and the looper. The loop stops if the looper is freed.
@MainActor
final class LoopingPlayer {
    let player = AVQueuePlayer()
    private var looper: AVPlayerLooper?
    private var url: URL?

    init() {
        player.isMuted = true
        player.preventsDisplaySleepDuringVideoPlayback = false
    }

    func load(_ url: URL) {
        guard url != self.url else { return }
        self.url = url
        looper?.disableLooping()
        player.removeAllItems()
        looper = AVPlayerLooper(player: player, templateItem: AVPlayerItem(url: url))
    }
}

struct LoopingVideoView: UIViewRepresentable {
    let url: URL
    var isPlaying = true

    func makeCoordinator() -> LoopingPlayer { LoopingPlayer() }

    func makeUIView(context: Context) -> PlayerLayerView {
        let view = PlayerLayerView()
        view.backgroundColor = .clear
        view.playerLayer.backgroundColor = UIColor.clear.cgColor
        view.playerLayer.videoGravity = .resizeAspect
        view.playerLayer.player = context.coordinator.player
        return view
    }

    func updateUIView(_ view: PlayerLayerView, context: Context) {
        let loop = context.coordinator
        loop.load(url)
        if isPlaying {
            loop.player.play()
        } else {
            loop.player.pause()
        }
    }

    static func dismantleUIView(_ view: PlayerLayerView, coordinator: LoopingPlayer) {
        coordinator.player.pause()
        view.playerLayer.player = nil
    }
}
What LoopingVideoView plays: a muted square clip that loops without a cut, for as long as the coordinator holds the looper.

Keep the looper alive

Apple’s AVPlayerLooper documentation says it "provides a much simpler interface to loop a single AVPlayerItem" than driving an AVQueuePlayer by hand. It treats your item as a template and puts at least three copies of it in the player’s queue, so the next pass is loaded before the current one ends. Seeking back to zero at the end of the item can show a stall at the join, and the looper avoids it.

The looper works only while something holds it. Create it as a local inside makeUIView and the loop stops soon after the function returns, which is why it lives in the coordinator here.

Changes to the template item after you create the looper do not reach the copies. If a clip never appears, check the looper’s status: when it reads failed, its error property says why.

Pause off-screen and in the background

A playing loop keeps its decoder busy whether anyone can see it or not. Pause it in onDisappear, and pause it whenever scenePhase leaves active, which covers the app switcher and an incoming call.

On iOS an AVPlayer keeps the screen awake while video plays, because preventsDisplaySleepDuringVideoPlayback defaults to true. LoopingPlayer sets it to false so browsing screens can sleep. Set it back to true on a workout screen the user watches without touching.

Muting stops the clip making sound. If the app has no sound of its own that should interrupt the user’s music, set the audio session category to ambient, which Apple describes as mixing your audio with other apps.

struct ExerciseClip: View {
    let slug: String
    @Environment(\.scenePhase) private var scenePhase
    @State private var onScreen = false

    var body: some View {
        ZStack {
            Image(slug) // the poster still, from the asset catalogue
                .resizable()
                .scaledToFit()
            if let url = Bundle.main.url(forResource: slug, withExtension: "mp4") {
                LoopingVideoView(url: url, isPlaying: onScreen && scenePhase == .active)
            }
        }
        .aspectRatio(1, contentMode: .fit)
        .onAppear { onScreen = true }
        .onDisappear { onScreen = false }
    }
}

Transparent HEVC on a clear layer

Apple platforms play HEVC with an alpha channel from iOS 13, and AVPlayerLayer composites it over whatever sits behind it. The view and layer above are already clear, so a transparent .mov needs no change to LoopingVideoView.

Leave the poster out from under a transparent clip, or it shows through. The alpha file is several times the size of an H.264 MP4, so use it only where the clip has to sit on a colour, a gradient or a photo.

struct TransparentClip: View {
    let slug: String
    @Environment(\.scenePhase) private var scenePhase
    @State private var onScreen = false

    var body: some View {
        if let url = Bundle.main.url(forResource: slug, withExtension: "mov") {
            LoopingVideoView(url: url, isPlaying: onScreen && scenePhase == .active)
                .aspectRatio(1, contentMode: .fit)
                .onAppear { onScreen = true }
                .onDisappear { onScreen = false }
        }
    }
}

// On any background, with no poster underneath:
TransparentClip(slug: "goblet-squat")
    .padding(24)
    .background(Color.indigo.gradient)
  • 222 KB

    the average lift as H.264 MP4

  • 1,124 KB

    the average lift as transparent HEVC

Dumbbell lateral raise with no background
Background colour
A lift with no background, the way a transparent .mov sits on a clear layer. Switch the colour behind it.

Lists: posters and one player

Every player that is showing video holds its own decoder and buffers, so a list of fifty playing rows is fifty players. Show a poster still in every row and play the loop only in the row the user opens.

Here a tap swaps a row’s poster for the clip, and only one row plays at a time. Close the row and SwiftUI dismantles the view, taking the player with it. Scroll it away and onDisappear pauses it.

struct Exercise: Identifiable {
    let slug: String
    let name: String
    let equipment: String
    var id: String { slug }
}

struct ExerciseList: View {
    let exercises: [Exercise]
    @State private var playing: String?

    var body: some View {
        List(exercises) { exercise in
            VStack(alignment: .leading, spacing: 8) {
                HStack(spacing: 12) {
                    Image(exercise.slug)
                        .resizable()
                        .frame(width: 56, height: 56)
                    VStack(alignment: .leading) {
                        Text(exercise.name)
                        Text(exercise.equipment)
                            .font(.subheadline)
                            .foregroundStyle(.secondary)
                    }
                }
                if playing == exercise.slug {
                    ExerciseClip(slug: exercise.slug)
                }
            }
            .contentShape(Rectangle())
            .onTapGesture {
                playing = playing == exercise.slug ? nil : exercise.slug
            }
        }
    }
}
Four lifts from a pull day, as rows of an exercise list. In the app each row shows its poster until it is tapped, and only that row plays.

Clips that suit this code

The code assumes square clips whose last frame meets the first, which is how the Setskit library ships: 720 by 720 pixels at 30 frames a second, an H.264 MP4 and a transparent HEVC .mov for every lift, and a poster still for each. The free sample at setskit.com/free-sample has five lifts in every format to try it with, and the integration guide at setskit.com/integration has the same player for Android, React Native, Flutter and the web.

  • 720 px

    square, at 30 frames a second

  • 3 s

    the median loop

  • 1,000

    lifts, each an MP4, a transparent .mov and a poster

Questions people ask

How do I loop a video in SwiftUI without a gap?
Give an AVQueuePlayer and the clip to an AVPlayerLooper inside a UIViewRepresentable, rather than seeking back to zero. The join is clean when the clip’s last frame meets its first.
Why does my AVPlayerLooper stop after one play?
Nothing is holding the looper, so it was freed. Store it in a property that lives as long as the view, such as the coordinator.
Can I loop only part of a video?
Yes. init(player:templateItem:timeRange:) loops just the time range you pass instead of the whole item.
Can SwiftUI’s VideoPlayer loop?
You can pass it an AVQueuePlayer driven by an AVPlayerLooper, and it will loop. It still shows its playback controls and keeps its layer to itself, so it suits a film better than a demo clip.

Sources