What is the best approach to retrieve playlists using MusicKit. I can't seem to guess from the docs how to use the API to accomplish this, as well as retrieving tracks from a playlist.
I am in the process of migrating code from Apple Music API to MusicKit and I potentially could use MusicDataRequest to retrieve playlists using the Apple Music API endpoints, but I want to be sure there are no better alternatives.
Sample code would definitely help.
Hello @ridmaur,
Given a Playlist identifier, you can create a MusicCatalogResourceRequest using the init(matching:equalTo:) initializer.
let playlistRequest = MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: "pl.ba2404fbc4464b8ba2d60399189cf24e")
let playlistResponse = try await playlistRequest.response()
if let playlist = playlistResponse.items.first {
print("\(playlist)")
} else {
print("Couldn't find playlist.")
}
Here's the corresponding console output:
Playlist(id: "pl.ba2404fbc4464b8ba2d60399189cf24e", name: "Hits in Spatial Audio", curatorName: "Apple Music Hits")
Given this instance of Playlist, you can get another instance that includes more properties, such as .tracks:
let detailedPlaylist = try await playlist.with([.tracks])
let tracks = detailedPlaylist.tracks ?? []
print("\(tracks)")
Here's the corresponding (abbreviated) console output:
MusicItemCollection<Track>(
items: [
Track.song(Song(id: "1440776809", title: "Moment 4 Life (feat. Drake)", artistName: "Nicki Minaj & Drake")),
Track.song(Song(id: "1603171970", title: "Less Than Zero", artistName: "The Weeknd")),
Track.song(Song(id: "1604411600", title: "Iffy", artistName: "Chris Brown")),
[...]
Track.song(Song(id: "1363310495", title: "Wasted Times", artistName: "The Weeknd")),
Track.song(Song(id: "1440907406", title: "MotorSport", artistName: "Migos, Nicki Minaj & Cardi B"))
],
hasNextBatch: true
)
You can also achieve the same result more efficiently, in a way that only issues one network request, by passing additional properties to be loaded directly as the MusicCatalogResourceRequest's properties:
var playlistRequest = MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: "pl.ba2404fbc4464b8ba2d60399189cf24e")
playlistRequest.properties = [.tracks]
let playlistResponse = try await playlistRequest.response()
if let playlist = playlistResponse.items.first {
print("\(playlist)")
let tracks = playlist.tracks ?? []
print("\(tracks)")
} else {
print("Couldn't find playlist.")
}
I hope this helps.
Best regards,