Streaming video is harder than playing a file, because viewers have different networks. A good service stores the same video at several qualities and lets the player switch between them as the connection changes. This is adaptive streaming, and on Apple platforms the standard format is HLS, recognised by an address ending in .m3u8. AVPlayer supports it without extra libraries.
SwiftUI gives you VideoPlayer, a view with the standard controls. The part that needs care is the lifecycle: a player holds decoders and memory, so you should stop it when the screen goes away and pause it when the app is no longer active. The project also shows how to watch an AVPlayerItem for loading and failure with Combine, so the screen can show a spinner or a clear error.
Concepts in this project
- Adaptive streaming: the player downloads small pieces and picks a quality for each from your current speed.
- HLS: an Apple format using a playlist file (.m3u8) that lists the pieces. AVPlayer reads it directly.
- VideoPlayer: SwiftUI's AVKit view with play, pause and a scrubber.
- KVO with Combine:
item.publisher(for: \.status)tells you when the item is ready or failed. - scenePhase: pause when the app is not active, unless you add background video on purpose.
- Cleaning up:
onDisappearpauses and removes the item, which frees memory and decoders.
Create the project
- In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product StreamPlayer.
- Delete the default ContentView.swift and the default @main file, then add the files below.
StreamPlayer/
VideoApp.swift @main
Video.swift list + duration format
VideoModel.swift AVPlayer + status
VideoScreen.swift player, state, list
StreamPlayerTests/
VideoTests.swift
The code
`Video.swift`
import Foundation
struct Video: Identifiable, Equatable {
let id = UUID()
let title: String
let url: URL
let note: String
}
// The first address is Apple's public HLS sample stream. Addresses like these can change,
// so replace them with streams you have the right to play (your own server or a video host).
enum SampleVideos {
static let all: [Video] = [
Video(title: "Apple HLS sample (adaptive)",
url: URL(string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8")!,
note: "Adaptive stream with several qualities"),
Video(title: "Your own video",
url: URL(string: "https://example.com/video/lesson-1.m3u8")!,
note: "Placeholder. Replace this address")
]
}
enum VideoFormat {
// 3725 -> "1:02:05", 125 -> "2:05"
static func duration(_ seconds: Double) -> String {
guard seconds.isFinite, seconds >= 0 else { return "0:00" }
let total = Int(seconds)
let hours = total / 3600
let minutes = (total % 3600) / 60
let secs = total % 60
if hours > 0 {
return "\(hours):\(String(format: "%02d", minutes)):\(String(format: "%02d", secs))"
}
return "\(minutes):\(String(format: "%02d", secs))"
}
}
`VideoModel.swift`
import AVKit
import Combine
import Observation
@Observable
@MainActor
final class VideoModel {
enum Status: Equatable {
case loading
case ready
case failed
}
private(set) var status: Status = .loading
let player = AVPlayer()
private var cancellable: AnyCancellable?
func play(_ video: Video) {
status = .loading
let item = AVPlayerItem(url: video.url)
// Watch the item so the screen can show a spinner or an error.
cancellable = item.publisher(for: \.status)
.receive(on: DispatchQueue.main)
.sink { [weak self] newStatus in
switch newStatus {
case .readyToPlay: self?.status = .ready
case .failed: self?.status = .failed
default: break
}
}
player.replaceCurrentItem(with: item)
player.play()
}
func stop() {
player.pause()
player.replaceCurrentItem(with: nil)
cancellable = nil
}
}
`VideoScreen.swift`
import SwiftUI
import AVKit
struct VideoScreen: View {
@State private var model = VideoModel()
@State private var selected = SampleVideos.all[0]
@Environment(\.scenePhase) private var scenePhase
var body: some View {
VStack(spacing: 0) {
ZStack {
VideoPlayer(player: model.player)
.aspectRatio(16 / 9, contentMode: .fit)
if model.status == .loading {
ProgressView().tint(.white)
}
if model.status == .failed {
Text("This video cannot be played right now.")
.foregroundStyle(.white)
.padding()
.background(.black.opacity(0.7), in: RoundedRectangle(cornerRadius: 8))
}
}
.background(Color.black)
Text(selected.title)
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
List(SampleVideos.all) { video in
Button {
selected = video
model.play(video)
} label: {
VStack(alignment: .leading) {
Text(video.title)
Text(video.note).font(.caption).foregroundStyle(.secondary)
}
}
}
.listStyle(.plain)
}
.onAppear { model.play(selected) }
.onDisappear { model.stop() }
.onChange(of: scenePhase) { _, phase in
// Pause when the app goes to the background (unless you add background video later).
if phase != .active { model.player.pause() }
}
}
}
`VideoApp.swift`
import SwiftUI
@main
struct VideoApp: App {
var body: some Scene {
WindowGroup {
VideoScreen()
}
}
}
`VideoTests.swift (in the tests target)`
import Testing
@testable import StreamPlayer
struct VideoTests {
@Test func shortDurations() {
#expect(VideoFormat.duration(0) == "0:00")
#expect(VideoFormat.duration(125) == "2:05")
}
@Test func hoursAreShown() {
#expect(VideoFormat.duration(3725) == "1:02:05")
}
@Test func badValues() {
#expect(VideoFormat.duration(-1) == "0:00")
#expect(VideoFormat.duration(.nan) == "0:00")
}
@Test func listHasAnHLSStream() {
#expect(SampleVideos.all.contains { $0.url.pathExtension == "m3u8" })
}
}
Walkthrough
SampleVideos lists two entries. The first is Apple's public HLS example stream, which is meant for developers to test with. Addresses on someone else's server can change or vanish, so replace them with streams you control or have the right to use. The second entry is a placeholder that will fail on purpose, so you can see the error state.
VideoModel owns one AVPlayer. play(_:) creates an AVPlayerItem for the chosen video, sets the status to loading and subscribes to the item's status. KVO is the older observation system used by Apple's frameworks, and publisher(for:) turns it into a Combine stream. When the status becomes ready or failed, the model updates its own state on the main queue. Storing the subscription in cancellable keeps it alive, and replacing it cancels the old one.
VideoScreen stacks the player, the title and the list. A ZStack puts a spinner over the player while loading and an error message over it when the item fails. The player has a 16:9 shape so the layout does not jump when the video starts. Tapping a row sets the selected video and calls play.
The lifecycle is handled in three places. onAppear starts the first video. onDisappear calls stop, which pauses, removes the current item and cancels the subscription. onChange(of: scenePhase) pauses the player when the app becomes inactive or goes to the background. Without these, a video can keep decoding after the user has left the screen.
The tests are small because most of the app is framework code. They check the time format, including hours and bad values, and that the sample list contains an HLS address. Playback itself is a manual test on a device or the Simulator with a real network.
How it works
- Choosing a video creates a new player item and shows the loading spinner.
- The status subscription reports ready or failed, and the overlay changes.
- The AVKit player handles controls, scrubbing and adaptive quality.
- Leaving the screen or the app pauses playback and frees the player item.
Expected output
The top of the screen shows the player with the standard controls. After a moment of buffering, shown with a spinner, the first video starts. Drag the scrubber to jump. Tap "Your own video" in the list: the title changes and, because the placeholder address does not exist, the message "This video cannot be played right now." appears and the app stays usable. Tap the first video again: it plays. Go to the Home screen: the video pauses. On a slower connection an adaptive stream lowers its quality instead of stopping. The four tests pass.
Your task
- Build the app and play the sample stream.
- Add your own HLS stream or a video file and show it in the list.
- Remember the playback position for each video with @AppStorage.
- Add Picture in Picture support through the Background Modes capability.
How to check it worked
- The spinner shows while loading and disappears when ready.
- Leaving the screen stops the player.
- You can explain what HLS and adaptive streaming are.
Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.