Sample CodeiOS, iPadOS, Mac CatalystReviewed 2026-07-21View on Apple Developer

Integrating CarPlay with Your Music App

At a glance

Item Summary
Purpose Configure your music app to work with CarPlay by displaying a custom UI.
App architecture A Swift sample with the source-visible chain AppDelegateAppleMusicAPIControllerNowPlayingViewModelIntentHandlerCarPlay APIs.
Main patterns View-controller organization, Protocol-oriented abstraction, Delegate or data-source callbacks
Project style 13 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries.
Execution model Source-visible boundaries: DispatchQueue.global.async, DispatchQueue.main.async; none alone proves a background thread.
State/event model Source-visible mechanisms: SwiftUI state property wrapper, NotificationCenter, ObservableObject.
Key frameworks/packages Foundation, MediaPlayer, os, UIKit, CarPlay; these are source dependencies, not architecture labels.

Project structure

Source bundle/
├── CarPlayMusic/
│   ├── App Lifecycle/
│   │   ├── AppDelegate.swift
│   │   ├── PlayerController.swift
│   │   ├── LoggerViewController.swift
│   │   ├── LoggerWindowSceneDelegate.swift
│   │   └── TemplateApplicationSceneDelegate.swift
│   ├── Apple Music/
│   │   ├── AppleMusicAPIController.swift
│   │   ├── AppleMusicAPIStructures.swift
│   │   ├── MediaPlayerUtilities.swift
│   │   └── DateDecoder.swift
│   ├── Helpers/
│   │   └── Logger.swift
│   └── Template Manager/
│       └── TemplateManager.swift
└── CarPlayMusicIntent/
    └── IntentHandler.swift

Structure observations

  • Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
  • Primary languages: Swift.
  • The verified tree contains 8 project/configuration file(s) and 60 source declaration(s).

Overall architecture

Reference code

CarPlayMusic/App Lifecycle/AppDelegate.swift:14 — architecture anchor

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    // ...
    func applicationDidBecomeActive(_ application: UIApplication) {
        MemoryLogger.shared.appendEvent("Application did become active.")
    }
    // ...
}

Interpretation

The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into CarPlay.

Ownership and state

Ownership evidence

CarPlayMusic/Apple Music/AppleMusicAPIController.swift:22 — stored dependency or nearest verified ownership anchor

class AppleMusicAPIController {
    // ...
    static let sharedController = AppleMusicAPIController()
    // ...
}
Owner Object or state Relationship Mutation authority
AppleMusicAPIController AppleMusicAPIController (sharedController) creates and retains Initialized by the owner; the binding is immutable
AppleMusicAPIController Bool (useAppleMusic) owns value state App/module collaborators
AppleMusicAPIController Bool (allowExplicitContent) owns value state App/module collaborators
AppleMusicAPIController TokenStorage (tokenStorage) creates and retains Owning lexical scope

Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Queue scheduling DispatchQueue.global.async The source addresses a global dispatch queue; no stable thread identity is implied. CarPlayMusic/App Lifecycle/AppDelegate.swift:44
Queue scheduling DispatchQueue.main.async The source addresses the main dispatch queue. CarPlayMusic/App Lifecycle/AppDelegate.swift:123

@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.

Reference code

CarPlayMusic/App Lifecycle/AppDelegate.swift:44 — representative execution boundary

        DispatchQueue.global(qos: .userInitiated).async {
            // ...
            let context = INMediaUserContext()
            // ...
        }

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
State propagation SwiftUI state property wrapper A SwiftUI property wrapper supplies or observes UI state. CarPlayMusic/App Lifecycle/PlayerController.swift:15
State propagation NotificationCenter NotificationCenter distributes named process-local events. CarPlayMusic/App Lifecycle/PlayerController.swift:57
State propagation ObservableObject ObservableObject supplies an observation contract. CarPlayMusic/App Lifecycle/PlayerController.swift:68
Source import Foundation The cited file imports this module; runtime use and architectural role are not inferred. CarPlayMusic/Apple Music/AppleMusicAPIController.swift:8
Source import MediaPlayer The cited file imports this module; runtime use and architectural role are not inferred. CarPlayMusic/App Lifecycle/AppDelegate.swift:11
Source import os The cited file imports this module; runtime use and architectural role are not inferred. CarPlayMusic/App Lifecycle/AppDelegate.swift:10
Source import UIKit The cited file imports this module; runtime use and architectural role are not inferred. CarPlayMusic/App Lifecycle/AppDelegate.swift:8
Source import CarPlay The cited file imports this module; runtime use and architectural role are not inferred. CarPlayMusic/App Lifecycle/TemplateApplicationSceneDelegate.swift:8

receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.

Class and protocol design

CarPlayMusic/Helpers/Logger.swift:26 — representative type boundary

protocol LoggerDelegate: AnyObject {

    /// The logger has received a new event.
    func loggerDidAppendEvent()
}
Type Responsibility Depends on or conforms to
AppDelegate Receives callback-driven events UIResponder, UIApplicationDelegate
LoggerDelegate Defines a capability or collaboration contract AnyObject
AppleMusicAPIController View lifecycle, callbacks, and feature coordination Concrete collaborators/imported frameworks
PlayerController View lifecycle, callbacks, and feature coordination View
NowPlayingViewModel UI-facing state and feature coordination ObservableObject, Identifiable
LoggerViewController View lifecycle, callbacks, and feature coordination UITableViewController
LoggerWindowSceneDelegate Receives callback-driven events NSObject, UIWindowSceneDelegate
TemplateApplicationSceneDelegate Receives callback-driven events NSObject
TemplateManager Long-lived feature or framework coordination NSObject
IntentHandler Handles callbacks or feature events INExtension, INPlayMediaIntentHandling, INAddMediaIntentHandling

The source explicitly defines local protocol relationships: MemoryLoggerLogger, LoggerViewControllerLoggerDelegate.

Access control

Symbol Access Verified effect Likely rationale
registerForSpotlight (CarPlayMusic/App Lifecycle/AppDelegate.swift:136) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: hide an implementation step that is not part of the collaboration surface.
cellIdentifier (CarPlayMusic/App Lifecycle/LoggerViewController.swift:14) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
formatter (CarPlayMusic/App Lifecycle/LoggerViewController.swift:15) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
datasource (CarPlayMusic/App Lifecycle/LoggerViewController.swift:16) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.

Reference code

CarPlayMusic/App Lifecycle/AppDelegate.swift:136 — representative boundary

    private func registerForSpotlight(mediaItem: INMediaItem, identifier: String) {
        // ...
            return type == .playlist ? "MPMediaGrouping.playlist" :
        // ...
    }

Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.

Logic ownership and placement

Logic Owning type or file Placement rationale
View lifecycle, callbacks, and feature coordination AppleMusicAPIController, LoggerViewController, PlayerController The source’s Controller suffix makes this role explicit.
Receives callback-driven events AppDelegate, LoggerDelegate, LoggerWindowSceneDelegate, TemplateApplicationSceneDelegate The source’s Delegate suffix makes this role explicit.
Handles callbacks or feature events IntentHandler The source’s Handler suffix makes this role explicit.
Long-lived feature or framework coordination TemplateManager The source’s Manager suffix makes this role explicit.
UI-facing state and feature coordination NowPlayingViewModel The source’s ViewModel suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization CarPlayMusic/Apple Music/AppleMusicAPIController.swift:14 A controller is the verified coordination boundary; this is MVC-style only where a separate model is present.
Protocol-oriented abstraction CarPlayMusic/Helpers/Logger.swift:33 A local protocol and concrete conformance create an explicit capability boundary.
Delegate or data-source callbacks CarPlayMusic/App Lifecycle/AppDelegate.swift:15 Callback protocols invert event delivery back into the sample’s owner.

Naming conventions

  • Types: Controller: AppleMusicAPIController, LoggerViewController, PlayerController; Delegate: AppDelegate, LoggerDelegate, LoggerWindowSceneDelegate, TemplateApplicationSceneDelegate; Handler: IntentHandler; Manager: TemplateManager; ViewModel: NowPlayingViewModel.
  • Protocols: LoggerDelegate, Logger.
  • Methods: applicationDidBecomeActive, applicationWillResignActive, applicationDidEnterBackground, applicationWillEnterForeground, applicationWillTerminate, application, resolveTerm, handle.
  • Files: CarPlayMusic/App Lifecycle/AppDelegate.swift, CarPlayMusic/Apple Music/AppleMusicAPIController.swift, CarPlayMusic/App Lifecycle/PlayerController.swift, CarPlayMusic/Apple Music/MediaPlayerUtilities.swift, CarPlayMusic/App Lifecycle/LoggerViewController.swift, CarPlayMusic/App Lifecycle/LoggerWindowSceneDelegate.swift.

Architecture takeaways

  • AppDelegate is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches MediaPlayer, UIKit, CarPlay, Intents through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
  • Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
  • Access-control conclusions separate verified language visibility from the likely design rationale.
  • Local protocol relationships provide an explicit substitution boundary.

Source map

Source file Relevant symbols
CarPlayMusic/App Lifecycle/AppDelegate.swift Cited implementation, DispatchQueue.global.async, DispatchQueue.main.async, MediaPlayer, os, UIKit, AppDelegate
CarPlayMusic/Apple Music/AppleMusicAPIController.swift Cited implementation, AppleMusicAPIController, Foundation, SearchType, ChartType
CarPlayMusic/Helpers/Logger.swift LoggerDelegate, Cited implementation, Event, Logger, MemoryLogger
CarPlayMusic/App Lifecycle/LoggerViewController.swift Cited implementation, LoggerViewController
CarPlayMusic/App Lifecycle/PlayerController.swift SwiftUI state property wrapper, NotificationCenter, ObservableObject, PlayerController, NowPlayingViewModel
CarPlayMusic/App Lifecycle/TemplateApplicationSceneDelegate.swift CarPlay, TemplateApplicationSceneDelegate
CarPlayMusic/Apple Music/AppleMusicAPIStructures.swift Storefront, CodingKeys, StorefrontAttributes, StorefrontResponse, Artist, ArtistAttributes, ArtistRelationship, ArtistRelationships, ArtistResponse, Album, AlbumAttributes, AlbumRelationship, AlbumRelationships, AlbumResponse, TrackRelationship, Artwork, EditorialNotes, PlayParameters, Genre, GenreAttributes, GenreRelationship, GenreResponse, Song, SongAttributes, SongRelationships, SongResponse, Station, StationAttributes, StationRelationship, StationResponse, Preview, Playlist, PlaylistAttributes, PlaylistRelationship, PlaylistRelationships, PlaylistResponse, Error, ErrorSource, SearchResponse, SearchResults, ChartsResponse, ChartResults, Chart
CarPlayMusic/Apple Music/MediaPlayerUtilities.swift MediaPlayerUtilities, func
CarPlayMusic/App Lifecycle/LoggerWindowSceneDelegate.swift LoggerWindowSceneDelegate
CarPlayMusic/Template Manager/TemplateManager.swift TemplateManager
CarPlayMusicIntent/IntentHandler.swift IntentHandler
CarPlayMusic/Apple Music/DateDecoder.swift DateDecoder
CarPlayMusic/Helpers/TokenStorage.swift TokenStorage