Musickit

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導 iOS 開發者使用 MusicKit 整合 Apple Music 搜尋、訂閱檢查、播放與正在播放中繼資料。

功能
此技能提供參考說明與 Swift 程式碼範例,用於透過 MusicKit 和 MediaPlayer 為 iOS 應用程式加入 Apple Music 功能。內容涵蓋專案設定、授權、目錄搜尋、訂閱檢查、使用 ApplicationMusicPlayer 播放、佇列管理、正在播放資訊與遠端指令處理。也包含常見錯誤表與審查清單。
適用情境
在為 iOS 應用程式加入音樂搜尋、Apple Music 訂閱流程、佇列管理、播放控制、遠端指令處理或正在播放資訊時使用。也適合用來審查或除錯現有的 MusicKit 整合。
執行需求
需要一個 iOS 應用程式專案,並為該 bundle ID 啟用 MusicKit App Service,在 Info.plist 中加入 NSAppleMusicUsageDescription,背景播放還需啟用 audio 背景模式。使用 MusicKit 與 MediaPlayer 框架。不包含指令碼,僅為說明文件。

MusicKit

Search the Apple Music catalog, manage playback with ApplicationMusicPlayer, check subscriptions, and publish Now Playing metadata via MPNowPlayingInfoCenter and MPRemoteCommandCenter.

Contents

Workflow

  1. Verify the MusicKit App Service, bundle identifier, purpose string, and background-audio mode before debugging code.
  2. Request authorization, then model every non-authorized state explicitly.
  3. Search or load catalog content and check MusicSubscription.current before queueing playback.
  4. Choose ApplicationMusicPlayer for app-scoped playback; wire Now Playing and remote commands only when the app owns those surfaces.
  5. 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

  1. Enable the MusicKit App Service for the app's explicit bundle ID in the Apple Developer portal so MusicKit can generate developer tokens automatically.
  2. Add NSAppleMusicUsageDescription to Info.plist explaining why the app accesses the user's media library.
  3. For background playback, add the audio background mode to UIBackgroundModes.

Imports

swift
import MusicKit       // Catalog, auth, playbackimport 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.

swift
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 promptinglet 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.

swift
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

swift
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.

swift
func checkSubscription() async throws -> Bool {    let subscription = try await MusicSubscription.current    return subscription.canPlayCatalogContent}
// Observe subscription changesfunc 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.

swift
import MusicKitimport 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.

swift
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

swift
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.

swift
// Initialize with multiple itemsfunc playAlbum(_ album: Album) async throws {    player.queue = [album]    try await player.play()}
// Append songs to the existing queuefunc appendToQueue(_ songs: [Song]) async throws {    try await player.queue.insert(songs, position: .tail)}
// Insert song to play nextfunc 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.

swift
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

swift
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.

swift
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

swift
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

MistakeFix
Debugging authorization before configuring the App Service and purpose stringVerify service, bundle ID, and NSAppleMusicUsageDescription first.
Queueing catalog content without a subscription gateCheck canPlayCatalogContent; offer subscription only when canBecomeSubscriber.
Using SystemMusicPlayer for app-owned playbackUse ApplicationMusicPlayer; the system player changes the Music app's global queue.
Publishing Now Playing metadata onceRefresh it on track, duration, rate, and elapsed-time changes.
Registering unsupported remote commandsDisable them; supported handlers must perform the action and return .success.

Review Checklist

  • MusicKit App Service enabled for the app's explicit bundle ID
  • NSAppleMusicUsageDescription added to Info.plist
  • MusicAuthorization.request() called before any MusicKit access
  • Subscription checked before attempting catalog playback
  • canBecomeSubscriber checked before presenting a subscription offer
  • hasCloudLibraryEnabled checked before library writes
  • ApplicationMusicPlayer used (not SystemMusicPlayer) 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 .success for 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

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/musickit提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新