Someone starts a track with the phone closed, then opens it. The player expands into the larger layout: the artwork grows and the controls rearrange.

The song starts again from the beginning.

The layout transition did what it was designed to do. It also exposed an ownership bug that had been in the app for years: playback belonged to a view, and the view was replaced.

Foldable hardware makes this defect impossible to miss, because the layout changes while the person is holding the device and listening. The same bug has always been reachable through rotation, a split-view resize on iPad, a navigation push that rebuilds the hierarchy, and state restoration. It was only less visible there.

How a view ends up owning the audio

This is the shape of the code behind the restart. Each line is reasonable in isolation:

SwiftGitHub
import SwiftUI
import AVFoundation

struct FragilePlayerScreen: View {
    let url: URL
    @State private var player = AVPlayer()

    var body: some View {
        Button("Pause") { player.pause() }
            .onAppear {
                player.replaceCurrentItem(with: AVPlayerItem(url: url))
                player.play()
            }
            .onDisappear {
                player.pause()
            }
    }
}

@State ties the player's lifetime to this view's identity. When a parent switches between a compact and an expanded layout with an if/else, SwiftUI treats the two branches as different views. The compact one is removed, its state is destroyed, and the expanded one is created with a new AVPlayer that loads the item and plays from zero. onAppear and onDisappear turn every structural change into a media command.

Nothing here is a misuse of SwiftUI. The framework is managing view lifetime correctly. The audio was simply attached to the wrong lifetime.

A session with presentations underneath it

The repair is a separation that holds on every platform:

  • A playback session owns the current item, the position, what the user asked for, and the transport state.
  • A presentation owns how those facts are drawn in one particular scene, at one particular size.

If the product promises continuous playback, the session has to outlive any single layout. Presentations are disposable.

SwiftGitHub
import Observation

@MainActor
@Observable
final class PlaybackSession {
    private let player: AVPlayer

    private(set) var currentTrackID: String?
    private(set) var userWantsPlayback = false
    private(set) var isInterrupted = false
    private(set) var itemReplacementCount = 0
    private(set) var expression = PlaybackSession.neutralExpression

    static let neutralExpression = 0.5

    init(player: AVPlayer = AVPlayer()) {
        self.player = player
    }

    func load(trackID: String, url: URL) {
        guard trackID != currentTrackID else { return }
        currentTrackID = trackID
        itemReplacementCount += 1
        player.replaceCurrentItem(with: AVPlayerItem(url: url))
        if userWantsPlayback, !isInterrupted { player.play() }
    }

    func play() {
        userWantsPlayback = true
        if !isInterrupted { player.play() }
    }

    func pause() {
        userWantsPlayback = false
        player.pause()
    }

    func interruptionBegan() {
        isInterrupted = true
    }

    func interruptionEnded(shouldResume: Bool) {
        isInterrupted = false
        if shouldResume, userWantsPlayback { player.play() }
    }

    func setExpression(_ value: Double?) {
        expression = value.map { min(max($0, 0), 1) } ?? Self.neutralExpression
    }
}

This is the ownership kernel of a player. A shipping one also observes timeControlStatus, surfaces item errors, handles route changes, and configures the audio session. Three details in the kernel carry the argument.

load compares a track identity, not a URL. Streaming URLs are frequently signed and expire; the same track can arrive with a different URL a few minutes later. Comparing URLs would restart the track when the catalog refreshes. A product that supports deliberate replay of the same track needs an explicit restart() and should not get that behavior as a side effect of load.

itemReplacementCount exists so that a test can assert that a layout change replaced nothing. More on that below.

userWantsPlayback and isInterrupted are separate facts, which matters as soon as a phone call arrives.

Put the owner above every layout decision

The session is created once, at the level whose lifetime matches the promise:

SwiftGitHub
struct PlayerApp: App {
    @State private var session = PlaybackSession()

    var body: some Scene {
        WindowGroup {
            PlayerRoot(session: session)
        }
    }
}

struct PlayerRoot: View {
    let session: PlaybackSession

    var body: some View {
        GeometryReader { proxy in
            if proxy.size.width >= 700 {
                ExpandedPlayer(session: session)
            } else {
                CompactPlayer(session: session)
            }
        }
    }
}

struct CompactPlayer: View {
    let session: PlaybackSession

    var body: some View {
        TransportButton(session: session)
    }
}

struct ExpandedPlayer: View {
    let session: PlaybackSession

    var body: some View {
        HStack(spacing: 32) {
            RoundedRectangle(cornerRadius: 24).aspectRatio(1, contentMode: .fit)
            TransportButton(session: session)
        }
        .padding(32)
    }
}

struct TransportButton: View {
    let session: PlaybackSession

    var body: some View {
        Button(session.userWantsPlayback ? "Pause" : "Play") {
            if session.userWantsPlayback { session.pause() } else { session.play() }
        }
    }
}

The if/else still swaps one view for another, and any @State inside CompactPlayer is still discarded when the width crosses the threshold. That is fine now. Scroll offsets and a half-open lyrics panel are presentation state; losing them on a layout change is at worst a small annoyance. The session sits above the branch and is untouched.

The 700-point threshold is a design breakpoint measured on the container. It is not a device check, and the same root works in an iPad split view.

Where the owner should live depends on what the product promises. One session in the App means every window controls the same playback, which suits a music app. A session per scene means each window plays independently, which then requires a decision about which one holds the audio. A singleton and a scene-local object are both correct for some product, so choose from the promise and write it down.

Geometry tells you the space; the hinge tells you the angle

iOS 27.1 added hinge reporting: UIHingeInteraction in UIKit and onHingeChange in SwiftUI, each delivering a hinge status (closed, partially open, fully open) and an angle. Apple's guidance for iPhone Duo keeps two jobs apart, and I would treat that as a hard rule:

  • Layout responds to the size and arrangement the scene is given. A reading layout must never estimate its width from the hinge angle.
  • Hinge input is for interactions that really are about the hinge, such as bending a pitch or scrubbing by tilting the upper half.

An adapter that maps the hinge to a musical parameter looks like this:

SwiftGitHub
@available(iOS 27.1, *)
struct HingeExpression: ViewModifier {
    let session: PlaybackSession

    func body(content: Content) -> some View {
        content.onHingeChange { _, context in
            guard let hinge = context.hinge,
                  hinge.status == .partiallyOpen else {
                session.setExpression(nil)
                return
            }
            session.setExpression(hinge.angle.degrees / 180)
        }
    }
}

context.hinge is optional. The SDK documents that it becomes nil when the view leaves a hierarchy that provides hinge updates, and the same code runs on every device that has no hinge at all. The modifier returns the parameter to a neutral value in that case. Without that line, a pitch bend is left at whatever extreme it had when the phone was closed, and the next track plays out of tune with no control on screen to fix it.

Dividing by 180 assumes a fully open device reports 180 degrees. I have compiled this against the SDK and have not run it on hardware, so treat the mapping as something to calibrate on a device.

The session exposes setExpression and knows nothing about hinges. A slider, a keyboard shortcut, and an accessibility action call the same method. The hinge is one optional input path, and the feature must be complete without it.

Changing a parameter is not rebuilding the engine

For an AVAudioEngine graph, a geometry or hinge update should change a value on an existing node. Stopping the engine, reconnecting nodes, and starting again on every update produces clicks and gaps, and during a continuous gesture it happens dozens of times per second.

Decide in advance which changes need a reconfiguration (sample rate, channel layout, adding an effect) and which are parameter changes on a running graph (gain, pitch, filter cutoff). Ramp continuous parameters over a few milliseconds so a jump in the hinge angle does not become a jump in the waveform.

The real-time boundary runs both ways. UI callbacks must not block waiting on the render thread. A render callback must not take a lock held by the main thread, allocate memory, call into Swift concurrency, or touch the network. An actor is a good owner for the session's asynchronous logic and is the wrong tool for communicating with a render callback, which needs an atomic value or a lock-free queue.

Keep the user's intent apart from the system's permission

A user pressing Pause and a phone call interrupting audio both stop the sound. They are different events, and the difference decides what happens when the call ends.

SwiftGitHub
@available(iOS 27.0, *)
@MainActor
final class AudioSessionAdapter {
    private let session: PlaybackSession
    private var observers: [any NSObjectProtocol] = []

    init(session: PlaybackSession) {
        self.session = session
        let center = NotificationCenter.default
        let audioSession = AVAudioSession.sharedInstance()

        observers.append(center.addObserver(
            forName: AVAudioSession.didBecomeInactiveNotification,
            object: audioSession, queue: .main
        ) { [weak self] notification in
            let context = notification.userInfo?[AVAudioSession.deactivationContextKey]
                as? AVAudioSession.DeactivationContext
            MainActor.assumeIsolated {
                guard context?.source == .system else { return }
                self?.session.interruptionBegan()
            }
        })

        observers.append(center.addObserver(
            forName: AVAudioSession.resumptionRecommendationNotification,
            object: audioSession, queue: .main
        ) { [weak self] notification in
            let context = notification.userInfo?[AVAudioSession.resumptionContextKey]
                as? AVAudioSession.ResumptionContext
            MainActor.assumeIsolated {
                self?.session.interruptionEnded(
                    shouldResume: context?.recommendation == .shouldResume
                )
            }
        })
    }
}

The adapter translates framework notifications into two domain events and decides nothing else. The session combines them with intent: playback resumes only if the system recommends it and the user still wants playback. If the user pressed Pause on the lock screen during the call, userWantsPlayback is false and the music stays off.

Calling player.play() unconditionally when an interruption ends is how apps start playing in a quiet room after an alarm.

A note on the API, because it changed recently. The iOS 27 SDK deprecates AVAudioSession.interruptionNotification and its InterruptionType and InterruptionOptions values, and points to the two notifications used above: one when the session becomes inactive, carrying a context that says whether the app or the system deactivated it, and one carrying the system's recommendation on resuming. The compiler will tell you: an adapter written against the older notification builds with deprecation warnings that name the replacements. An app that still deploys to earlier releases observes the older notification there and maps its began and ended events onto the same two session methods. That is the practical argument for the adapter. The audio session API changed underneath it, and PlaybackSession did not need to.

The context objects are read out of userInfo before hopping to the main actor because Notification is not Sendable, while the two context types are.

A disappearing view is not a stop command

onDisappear fires when the user navigates away, when a layout branch is replaced, when a sheet covers the view on some configurations, and when a scene is reconfigured. Pausing there assumes that all of those mean "the user wants silence". One of them does.

If leaving a particular screen should stop playback, for example a preview player in a store page, state that as a navigation rule: the coordinator that pops the screen tells the session to stop. Do not infer it from a view lifecycle callback.

The reverse also needs care. Keeping playback alive does not mean keeping everything alive. Artwork downloads, waveform rendering, and lyric timing observers belong to a presentation and should be cancelled with it, which .task does for free. Separate lifetimes are what let the app drop all of that work during a transition while the audio continues.

Measure continuity at the media boundary

A screenshot cannot show that the audio was continuous. The evidence is in the session:

  • the number of item replacements across a layout transition (expected: zero);
  • engine starts and stops (expected: zero);
  • position before and after, compared with elapsed time;
  • interruption events and what followed each.

The session and the root above support a direct test: load a track, play, change the container width across the breakpoint, and assert itemReplacementCount == 1 and currentTrackID unchanged. Then test the legitimate path: load a different track and assert the count is 2. A design that achieves continuity by ignoring every load has traded one bug for another.

On a device, run the transitions in sequence without pausing between them: closed to open while playing, open to closed, a call during the transition, a Bluetooth route change, a new track selected while the layout is animating. If you publish a claim about gapless behavior, record how you measured it and on which hardware.

Every hinge interaction needs an equivalent control

A hinge gesture is an enhancement. Anything essential must also be reachable by touch, by keyboard where one is attached, and through VoiceOver and Switch Control, and each path should call the same session method so the result does not depend on how it was invoked.

I use a simple question to check the architecture: if the foldable presentation were deleted entirely, could I still describe a complete playback session? If yes, the device can change shape as often as it likes and the song carries on.

What to ask of your own player

  • Which object owns the AVPlayer or the engine, and what destroys that object?
  • Does any onAppear, onDisappear, or .task issue a media command?
  • Is track identity compared by ID or by URL?
  • What does each input adapter do when its sensor is unavailable?
  • After an interruption ends, what decides whether playback resumes?

The person holding the phone did one thing: they opened it. Every layer of the player should agree that nothing else happened.

References

If this edition sharpened your next review, you can buy me a coffee.