MusadoraKit

repository·main·Indexed 19 days ago

https://github.com/rryam/musadorakit

A Swift library that simplifies working with MusicKit and the Apple Music API. It provides high-level, one-liner API implementations for searching the music catalog, accessing charts, managing user libraries and playlists, fetching recommendations, and retrieving Apple Music Replay summaries via MSummary. The library also includes MHistory for library history, tools for managing content ratings and favorites, and the AnimatedArtworkView SwiftUI component for dynamic backgrounds.

Tokens
5.7K
Snippets
18
Records
22
Agent score
17%

What's inside MusadoraKit

  1. MusadoraKit API Overview

    main

    MusadoraKit is organized into several functional areas:

    Core APIs

    • Catalog: Search and browse the Apple Music catalog.
    • Library: Access the user's personal music library.
    • Recommendations: Retrieve personalized music suggestions.
    • History: Access recently played items.

    Music Features

    • Music Player: Simplified playback controls.
    • Music Summaries: Access Apple Music Replay data.
    • Ratings: Manage and rate music content.
    • Favorites: Manage favorite items.
    • Storefronts: Manage regional content.

    Other Features

    • Equivalents: Access clean or explicit content versions.
    • Batch Requests: Perform multiple resource requests in a single call.
    • AnimatedArtworkView: SwiftUI components for displaying artwork.
  2. Install MusadoraKit via Swift Package Manager

    main

    Add MusadoraKit to your project by including it in your Package.swift file using the following dependency declaration.

    dependencies: [
        .package(url: "https://github.com/rryam/MusadoraKit.git", .upToNextMajor(from: "10.2.0"))
    ]
  3. Setup MusicKit for your app

    main

    Before using MusadoraKit, you must configure your project to support Apple Music integration:

    1. Enable MusicKit: Go to the Apple Developer Portal and enable MusicKit for your specific Bundle Identifier.
    2. Configure Info.plist: Add the NSAppleMusicUsageDescription key to your Info.plist with a string explaining why your app needs access to the user's music library.
    3. Request Authorization: You must explicitly request permission from the user using MusicAuthorization.request().
    4. Install MusadoraKit: Add the framework to your project via Swift Package Manager.
  4. Configure MusicKit requirements

    main

    To use MusadoraKit and Apple Music, you must complete these three setup steps:

    1. Enable MusicKit in Apple Developer Portal

    • Visit the Apple Developer Portal.
    • Navigate to Certificates, Identifiers & Profiles > Identifiers.
    • Select your App's Bundle Identifier.
    • Under Services, ensure MusicKit is enabled.

    2. Add Usage Description to Info.plist

    Add the NSAppleMusicUsageDescription key to your Info.plist with a string explaining why your app needs access to the user's media library.

    3. Request Authorization

  5. Quick Start with MusadoraKit

    main

    MusadoraKit provides high-level, one-liner APIs to interact with Apple Music. You can quickly fetch library content, search the catalog, get recommendations, or access replay summaries using async/await.

    Ensure you have imported MusadoraKit before using these APIs.

    import MusadoraKit
    
    // Get user's Apple Music library
    let songs = try await MLibrary.songs()
    
    // Search the Apple Music catalog
    let results = try await MCatalog.search(for: "The Weeknd", types: [.songs, .albums])
    
    // Get personalized recommendations
    let recommendations = try await MRecommendation.default()
    
    // Access user's music summaries (Replay)
    let summary = try await MSummary.latest()
  6. Request Apple Music authorization

    main

    Use MusicAuthorization.request() from the native MusicKit framework to prompt the user for permission. MusadoraKit works alongside this standard authorization flow.

    import MusicKit
    import Observation
    
    @Observable
    class MusicAuthorizationManager {
        var isAuthorizedForMusicKit = false
        var musicKitError: MusicKitError? 
    
        func requestMusicAuthorization() async {
            let status = await MusicAuthorization.request()
    
            switch status {
            case .authorized:
                isAuthorizedForMusicKit = true
            case .restricted:
                musicKitError = .restricted
            case .notDetermined:
                musicKitError = .notDetermined
            case .denied:
                musicKitError = .denied
            @unknown default:
                musicKitError = .notDetermined
            }
        }
    }
  7. Quick Start: Search for music

    main

    You can perform a basic search in the music catalog using MCatalog.search. This method allows you to specify the search term, the types of items to return (e.g., .songs), and a limit.

    import MusadoraKit
    
    Task {
        do {
            let searchResponse = try await MCatalog.search(for: "The Weeknd", types: [.songs], limit: 5)
            print("Found \(searchResponse.songs.count) songs!")
        } catch {
            print("Search failed: \(error)")
        }
    }
  8. Access the 100 Best Albums collection

    main

    Access Apple's curated '100 Best Albums' collection using MRecommendation.

    // Get a specific album by position
    let album = try await MRecommendation.hundredBestAlbum(at: 1)
    
    // Get the entire collection
    let allAlbums = try await MRecommendation.allHundredBestAlbums(storefront: "gb")
  9. Test Apple Music API connectivity

    main

    Use MusadoraKit.test() to validate your developer token, MusicKit configuration, and network connectivity to the Apple Music API. This is useful for debugging setup issues like userAuthenticationRequired (token issues) or badServerResponse (configuration issues).

    Task {
        do {
            try await MusadoraKit.test()
            print("Successfully connected to Apple Music API!")
        } catch {
            print("Failed to connect: \(error.localizedDescription)")
    
            if let urlError = error as? URLError {
                switch urlError.code {
                case .userAuthenticationRequired:
                    print("Issue with developer token or MusicKit setup")
                case .badServerResponse:
                    print("Server error - check your configuration")
                default:
                    print("Network or other error")
                }
            }
        }
    }
  10. Manage content ratings and favorites with MCatalog

    main

    Use MCatalog to manage user ratings (like, dislike, love) and favorites for songs, albums, playlists, artists, music videos, and stations.

    // Ratings
    let songRating = try await MCatalog.addRating(for: song, rating: .like)
    let albumRating = try await MCatalog.addRating(for: album, rating: .dislike)
    let playlistRating = try await MCatalog.addRating(for: playlist, rating: .love)
    
    let currentSongRating = try await MCatalog.rating(for: song)
    try await MCatalog.deleteRating(for: song)
    
    // Favorites
    try await MCatalog.favorite(song: song)
    try await MCatalog.favorite(album: album)
    try await MCatalog.favorite(playlist: playlist)
    try await MCatalog.favorite(artist: artist)
    try await MCatalog.favorite(musicVideo: musicVideo)
    try await MCatalog.favorite(station: station)
  11. Fetch Apple Music recommendations

    main

    Use MRecommendation.default() to access Apple's Music recommendation system. This returns a collection of recommended items including albums, playlists, and stations.

    let recommendations = try await MRecommendation.default()
    
    guard let recommendation = recommendations.first else { return }
    
    print(recommendation.albums)
    print(recommendation.playlists)
    print(recommendation.stations)