musickit
dpearson2699/swift-ios-skills
Integrate Apple Music playback, catalog search, and Now Playing metadata into iOS apps.
What is musickit?
MusicKit enables searching the Apple Music catalog, managing playback with ApplicationMusicPlayer, checking subscriptions, and publishing Now Playing metadata to the Lock Screen and Control Center. Use it when building music search, subscription flows, queue management, playback controls, and remote command handling into iOS apps.
- Search the Apple Music catalog and display results with artwork
- Manage playback queues and control playback (play, pause, skip) with ApplicationMusicPlayer
- Check user subscription status and present Apple Music subscription offers
- Update Now Playing info on Lock Screen, Control Center, and CarPlay
- Handle remote commands from Lock Screen controls, AirPods gestures, and CarPlay
- Observe playback state changes and subscription updates
How to install musickit
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill musickit- Enable MusicKit App Service in Apple Developer portal for your bundle ID
- Add NSAppleMusicUsageDescription to Info.plist
- Enable audio background mode in UIBackgroundModes for background playback
- Request MusicAuthorization before accessing music data
How to use musickit
- 1.Request MusicAuthorization and handle authorized, denied, and restricted states
- 2.Search the catalog using MusicCatalogSearchRequest with a search term
- 3.Check MusicSubscription.current.canPlayCatalogContent before offering playback
- 4.Create an ApplicationMusicPlayer queue with songs or albums and call play()
- 5.Update MPNowPlayingInfoCenter with track metadata and artwork for Lock Screen display
- 6.Register MPRemoteCommandCenter handlers to respond to playback controls
Use cases
- Building a music search feature that queries Apple Music and plays results
- Adding background audio playback with Lock Screen controls to an existing app
- Implementing a subscription check before enabling playback features
- Displaying album artwork and track metadata on the Lock Screen
- Handling queue management (append, insert next, play album) during playback
- iOS app developers adding music playback features
- Developers building music discovery or streaming experiences
- Teams implementing subscription-gated playback flows
- Apps requiring Lock Screen and Control Center integration
musickit FAQ
Users need an active Apple Music subscription to play catalog content. You can check subscription status with MusicSubscription.current.canPlayCatalogContent and present a subscription offer sheet if needed.
No. ApplicationMusicPlayer plays content independently and does not affect the system Music app's state or queue.
Use MPNowPlayingInfoCenter to set track title, artist, duration, artwork, and playback rate. ApplicationMusicPlayer handles this automatically for Apple Music content.
Request MusicAuthorization before accessing music data. Add NSAppleMusicUsageDescription to Info.plist explaining why the app accesses the media library.
Yes. Register handlers with MPRemoteCommandCenter to respond to play, pause, skip, and seek commands from Lock Screen, AirPods, and CarPlay.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: musickit description: "Integrate Apple Music playback, catalog search, and Now Playing metadata using MusicKit and MediaPlayer. Use when adding music search, Apple Music subscription flows, queue management, playback controls, remote command handling, or Now Playing info to iOS apps."
MusicKit
Search the Apple Music catalog, manage playback with ApplicationMusicPlayer,
check subscriptions, and publish Now Playing metadata via MPNowPlayingInfoCenter
and MPRemoteCommandCenter.
Contents
- Setup
- Workflow
- Authorization
- Catalog Search
- Subscription Checks
- Playback with ApplicationMusicPlayer
- Queue Management
- Now Playing Info
- Remote Command Center
- Common Mistakes
- Review Checklist
- References
Workflow
- Verify the MusicKit App Service, bundle identifier, purpose string, and background-audio mode before debugging code.
- Request authorization, then model every non-authorized state explicitly.
- Search or load catalog content and check
MusicSubscription.currentbefore queueing playback. - Choose
ApplicationMusicPlayerfor app-scoped playback; wire Now Playing and remote commands only when the app owns those surfaces. - Test authorized, denied, unsubscribed, offline, queue failure, interruption, and track-change states. Fix the smallest failing layer, restore the fixture, and rerun the same state matrix.
Setup
Project Configuration
- Enable the MusicKit App Service for the app's explicit bundle ID in the Apple Developer portal so MusicKit can generate developer tokens automatically.
- Add
NSAppleMusicUsageDescriptionto Info.plist explaining why the app accesses the user's media library. - For background playback, add the
audiobackground mode toUIBackgroundModes.
Imports
import MusicKit // Catalog, auth, playback
import MediaPlayer // MPRemoteCommandCenter, MPNowPlayingInfoCenter
Authorization
Request permission before accessing the user's music data or playing Apple Music
content. request() presents Apple's consent dialog when necessary; use
currentStatus to read the current setting without prompting.
func requestMusicAccess() async -> MusicAuthorization.Status {
let status = await MusicAuthorization.request()
switch status {
case .authorized:
// Full access to MusicKit APIs
break
case .denied, .restricted:
// Show guidance to enable in Settings
break
case .notDetermined:
break
@unknown default:
break
}
return status
}
// Check current status without prompting
let current = MusicAuthorization.currentStatus
Catalog Search
Use MusicCatalogSearchRequest to search the Apple Music catalog. Catalog lookup
can fetch Apple Music resources, but playback of subscription catalog content
must still be gated on MusicSubscription.current.canPlayCatalogContent.
func searchCatalog(term: String) async throws -> MusicItemCollection<Song> {
var request = MusicCatalogSearchRequest(term: term, types: [Song.self])
request.limit = 25
let response = try await request.response()
return response.songs
}
Displaying Results
for song in songs {
print("\(song.title) by \(song.artistName)")
if let artwork = song.artwork {
let url = artwork.url(width: 300, height: 300)
// Load artwork from url
}
}
Subscription Checks
Check whether the user has an active Apple Music subscription before offering playback features.
func checkSubscription() async throws -> Bool {
let subscription = try await MusicSubscription.current
return subscription.canPlayCatalogContent
}
// Observe subscription changes
func observeSubscription() async {
for await subscription in MusicSubscription.subscriptionUpdates {
if subscription.canPlayCatalogContent {
// Enable full playback UI
} else {
// Show subscription offer
}
}
}
Offering Apple Music
Present the Apple Music subscription offer sheet when the user is not subscribed.
Check canBecomeSubscriber first, and pass MusicSubscriptionOffer.Options or
onLoadCompletion when the sheet needs contextual metadata or load-error handling.
import MusicKit
import SwiftUI
struct MusicOfferView: View {
@State private var showOffer = false
var body: some View {
Button("Subscribe to Apple Music") {
Task {
let subscription = try? await MusicSubscription.current
showOffer = subscription?.canBecomeSubscriber == true
}
}
.musicSubscriptionOffer(
isPresented: $showOffer,
options: .default,
onLoadCompletion: { error in
if let error {
// Surface loading errors in app UI or diagnostics.
print(error)
}
}
)
}
}
Playback with ApplicationMusicPlayer
ApplicationMusicPlayer plays Apple Music content independently from the Music app. It does not affect the system player's state.
let player = ApplicationMusicPlayer.shared
func playSong(_ song: Song) async throws {
player.queue = [song]
try await player.play()
}
func pause() {
player.pause()
}
func skipToNext() async throws {
try await player.skipToNextEntry()
}
Observing Playback State
func observePlayback() {
// player.state is an @Observable property
let state = player.state
switch state.playbackStatus {
case .playing:
break
case .paused:
break
case .stopped, .interrupted, .seekingForward, .seekingBackward:
break
@unknown default:
break
}
}
Queue Management
Build and manipulate the playback queue using ApplicationMusicPlayer.Queue.
// Initialize with multiple items
func playAlbum(_ album: Album) async throws {
player.queue = [album]
try await player.play()
}
// Append songs to the existing queue
func appendToQueue(_ songs: [Song]) async throws {
try await player.queue.insert(songs, position: .tail)
}
// Insert song to play next
func playNext(_ song: Song) async throws {
try await player.queue.insert(song, position: .afterCurrentEntry)
}
Now Playing Info
Update MPNowPlayingInfoCenter so the Lock Screen, Control Center, and CarPlay
display current track metadata. This is essential when playing custom audio
(non-MusicKit sources). ApplicationMusicPlayer handles this automatically for
Apple Music content.
import MediaPlayer
func updateNowPlaying(title: String, artist: String, duration: TimeInterval, elapsed: TimeInterval) {
var info = [String: Any]()
info[MPMediaItemPropertyTitle] = title
info[MPMediaItemPropertyArtist] = artist
info[MPMediaItemPropertyPlaybackDuration] = duration
info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = elapsed
info[MPNowPlayingInfoPropertyPlaybackRate] = 1.0
info[MPNowPlayingInfoPropertyMediaType] = MPNowPlayingInfoMediaType.audio.rawValue
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
}
func clearNowPlaying() {
MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
}
Adding Artwork
func setArtwork(_ image: UIImage) {
let artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
var info = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]
info[MPMediaItemPropertyArtwork] = artwork
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
}
Remote Command Center
Register handlers for MPRemoteCommandCenter to respond to Lock Screen controls,
AirPods tap gestures, and CarPlay buttons.
func setupRemoteCommands() {
let center = MPRemoteCommandCenter.shared()
center.playCommand.addTarget { _ in
resumePlayback()
return .success
}
center.pauseCommand.addTarget { _ in
pausePlayback()
return .success
}
center.nextTrackCommand.addTarget { _ in
skipToNext()
return .success
}
center.previousTrackCommand.addTarget { _ in
skipToPrevious()
return .success
}
// Disable commands you do not support
center.seekForwardCommand.isEnabled = false
center.seekBackwardCommand.isEnabled = false
}
Scrubbing Support
func enableScrubbing() {
let center = MPRemoteCommandCenter.shared()
center.changePlaybackPositionCommand.addTarget { event in
guard let positionEvent = event as? MPChangePlaybackPositionCommandEvent else {
return .commandFailed
}
seek(to: positionEvent.positionTime)
return .success
}
}
Common Mistakes
| Mistake | Fix |
|---|---|
| Debugging authorization before configuring the App Service and purpose string | Verify service, bundle ID, and NSAppleMusicUsageDescription first. |
| Queueing catalog content without a subscription gate | Check canPlayCatalogContent; offer subscription only when canBecomeSubscriber. |
Using SystemMusicPlayer for app-owned playback | Use ApplicationMusicPlayer; the system player changes the Music app's global queue. |
| Publishing Now Playing metadata once | Refresh it on track, duration, rate, and elapsed-time changes. |
| Registering unsupported remote commands | Disable them; supported handlers must perform the action and return .success. |
Review Checklist
- MusicKit App Service enabled for the app's explicit bundle ID
-
NSAppleMusicUsageDescriptionadded to Info.plist -
MusicAuthorization.request()called before any MusicKit access - Subscription checked before attempting catalog playback
-
canBecomeSubscriberchecked before presenting a subscription offer -
hasCloudLibraryEnabledchecked before library writes -
ApplicationMusicPlayerused (notSystemMusicPlayer) for app-scoped playback - Background audio mode enabled if music plays in background
- Now Playing info updated on every track change (for custom audio)
- Remote command handlers return
.successfor supported commands - Unsupported remote commands disabled with
isEnabled = false - Artwork provided in Now Playing info for Lock Screen display
- Elapsed playback time updated periodically for scrubber accuracy
- Subscription offer presented when user lacks Apple Music subscription
References
- Extended patterns (SwiftUI integration, genre browsing, playlist management): references/musickit-patterns.md
- MusicKit framework
- Using automatic developer token generation for Apple Music API
- MusicAuthorization
- ApplicationMusicPlayer
- MusicCatalogSearchRequest
- MusicSubscription
- canPlayCatalogContent
- canBecomeSubscriber
- hasCloudLibraryEnabled
- MusicCatalogChartsRequest initializer
- musicSubscriptionOffer(isPresented:options:onLoadCompletion:)
- MPRemoteCommandCenter
- MPNowPlayingInfoCenter
- NSAppleMusicUsageDescription
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

natural-language
Tokenize, tag, and analyze text with NaturalLanguage; translate with Translation framework.

paperkit
Add drawings, shapes, and markup editing to iOS apps with PaperKit's system-standard canvas.

passkit
Integrate Apple Pay payments and Wallet passes into iOS apps using PassKit.

pdfkit
Display, navigate, and annotate PDF documents in iOS/macOS apps with PDFKit.

pencilkit
Add Apple Pencil drawing, tool picker, and serialization to iOS/iPadOS apps.

permissionkit
Request parental permission for child communication in iOS apps via iMessage.