I'm trying to perform a search for a song by album, artist, & title in the cases when I don't know the song's id (or if there is no isrc match)
Reading the docs, it seems that I can only search for one term at a time, but against a list of MusicCatalogSearchable Types
So my strategy would be to search for albums by name, then filter the results by artist and title.
Two questions here, really:
Is the above a good strategy, or is there a better way to do this?
For the life of my I cannot figure out from the docs, what to put in place of [MusicCatalogSearchable.Album] in the below.
var albumRequest = MusicCatalogSearchRequest(term: album.name, types: [MusicCatalogSearchable.Album])
Xcode doesn't like the above and gives the following error:
Type 'MusicCatalogSearchable' has no member 'Album'
Sadly, everything I've tried, results in an error.
When I look in MusicKit, I see the below, which seems empty to me:
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public protocol MusicCatalogSearchable : MusicItem {
}
What am I missing?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi there,
tl;dr: How can I get the id of a curator and then with that get a listing of their playlists?
I asked about curators a while back, here in this forum, but I can’t find that post, so I’m writing a new one, esp. now new curator features have been added to MusicKit as of WWDC22.
Let's say that userB wants to access one of userA's playlists.
Since userB has no way of accessing userA’s library, userA’s playlist needs to be accessible as a catalog resource. This is accomplished by userA manually performing an action in the Music App on macOS or iOS (I wish this could be done programmatically, but no, and that’s off topic).
At present, the only way that I know of to determine if a playlist available as a catalog resource is by checking for the hasCatalog property under attributes and/or the globalId property under attributes.playParams.
@JoeKun once told me that globalId should be considered opaque and should not be relied upon.
That said, adding "include=catalog" to the request properties of a MusicDataRequest that fetches playlists from userA's Library, like the below will give me access to catalog ID.
var playlistRequestURLComponents = URLComponents()
playlistRequestURLComponents.scheme = "https"
playlistRequestURLComponents.host = "api.music.apple.com"
playlistRequestURLComponents.path = "/v1/me/library/playlists"
playlistRequestURLComponents.queryItems = [
URLQueryItem(name:"limit", value: "100"),
URLQueryItem(name:"include", value: "catalog")
]
Note that this can only be performed by userA.
And here comes the curator question:
If userB wants to get a list of all userA’s catalog playlists (or a specific one) how can that be done?
It seems I need to know userA’s curator ID and do some sort of request on that, or I could perhaps get the curator info by performing a MusicCatalogResourceRequest<Playlist> request, adding [.tracks, .moreByCurator] to the request.
On the former, I got no idea how to find userA’s curator ID, even if I’m coding with a scope that has Library access for userA. The best I can seem to do is get a curatorName when adding "include-catalog" (as above) to a MusicDataRequest that gets a user's library playlists.
On the latter, getting the catalog ID of a playlist requires userA to perform a MusicDataRequest against their library and passing that catalogID to userB so that userB can then access the tracks. This is what my app does now.
Ideally though, I'd like to somehow have userB get userA's curator ID and then have userB get userA's catalog playlists without having userA having to do the above.
Any thoughts on how to do this would be most appreciated.
First let me state that this is not an issue with MusicKit, but I've raised a radar on this and have received 0 response, which is, sadly, kinda normal.
However, it's kind of an important issue and my app relies on this feature to work consistently, so I thought I'd mention it and that the amazing @JoeKun might have an idea how to escalate it.
Here's the problem in the iOS Music app:
Add a song to an existing playlist
Add another song to the same playlist
Add another
View the playlist
More often than not, one of the newly added songs is missing in the playlist to which the song was added.
There are entries in Recently Added for newly added songs that are not in the playlist where the songs were added.
View the songs in the Music app on Mac.
Query the playlist to get all songs via the Apple Music API.
The Music app on Mac and the API results align, yet differ from iOS Music app.
There are entries in Recently Added for newly added songs that are not in the playlist where the songs were added.
In summary, when adding a song to a playlist using the iOS Music app, it sometimes does not add the song.
For the record, I am awaiting the confirmation message each time a song is added.
Adding tracks via the macOS Music app, seems to always work. This issue only occurs with the iOS app.
I'm slowly learning the new MusicKit beta for swift.
I've learned to successfully retrieve tracks of type Song using MusicDataRequest, using the following:
...
let countryCode = try await MusicDataRequest.currentCountryCode
if let url = URL(string: "https://api.music.apple.com/v1/catalog/\(countryCode)/songs?filter[isrc]=\(isrc)") {
let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url))
let dataResponse = try await dataRequest.response()
...
However, when I decode the data, there does not seem to be any album information that I can see.
I've tried adding includes=albums to the URL, but I don't think that's the right approach, because when I veiw the Song struct in MusicKit, I don't see a reference to an Album type anywhere.
Any advice on how to retrieve the album information would be most appreciated.
Thanks.
Hi there,
I just watched the WWDC22 vids on MusicKit enhancements.
In the Explore More Content with MusicKit video, there is a brief mention of "edit playlists" at 24:33.
I asked about this a couple years ago here in this forum.
The ever-helpful @JoeKun suggested that I submit a Feedback Assistant ticket on the need/justification for this feature, which I did some time ago: FB9798928. Sadly, there's been no traction on that.
I'm super hopeful that the ability to remove tracks from a library playlist is now, or at least will soon be, possible; however, I can't find anything in the docs yet to support this notion.
Am I being overly optimistic, or are we finally going to get this much requested feature?
Thanks.
Hi there,
I'm creating an iOS 15 app, using the new Swift MusicKit beta.
I've got basic "arbitrary" GET calls working with MusicDataRequest, like: fetch playlists and tracks.
However, I cannot find good docs for adding tracks to a playlist in a user's library.
I guess I could do this the "old way", but then I don't get the super-nice feature of auto dev/user tokens.
So the question is: how to a POST, instead of GET in the following:
let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists/`\(targetPlaylistId)/tracks")
let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url))
I've got an iOS app that performs a series of operations when initialized and when a refresh is performed.
In short, that app has:
An obervable object (appManager) that houses variables that act as "state" for the app.
Methods in the observable object that perform a variety of operations.
Here's an example:
Perform an API operation to get tokens to perform API actions on remote API service.
Perform a fetch on an external database to retrieve some data.
Decode that data an place the data into @Published variables, using (DispatchQueue.main.async).
Perform another remote API fetch operation on a different endpoint.
Put more variables in "state"
So when the user opens the app and after init runs, they see what they expect to see. And when they tap a "refresh" button, another function (e.g. getUpdatedAppData()) is called with similar steps to the above, and the app updates the published variables and the view(s) update.
The above steps are all performed using async functions, using Swift's new async/await functionality. Everything works swimmingly when the app is in the foreground.
What I'd like to do is perform the updateAppData() function using Background tasks as described here..
I have successfully setup the app to register and schedule a task, using BGTaskScheduler, and I can successfully emulate the triggerring of that task by setting a breakpoint and running the following code in the console:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.example.task"]
If the background tasks is something simple, like printing to the console, it seems to work
private func configureBackgroundTasks() {
Logger.log(.info, "Registering background tasks...")
let bgTaskIdentifier = "com.example.task"
BGTaskScheduler.shared.register(forTaskWithIdentifier: bgTaskIdentifier, using: DispatchQueue.main) { (task) in
Logger.log(.info, "Performing background task \(bgTaskIdentifier)")
task.setTaskCompleted(success: true)
backgroundTaskManager.scheduleAppRefresh()
}
}
However, if the function is something like the below, I can see the function being triggered, when simulating the running of the task, but the function hangs at the start of the first async operation (e.g. fetch tokens above).
It seems to "try to complete" (and usuually fails) once the app is brought to the foreground, but that's obviously not what I want to happen.
Surely, I'm misunderstanding something and/or doing something wrong, so I'm hoping to get some help here.
Thanks in advance for any assistance toward achieving what I'm trying to do here.
private func configureBackgroundTasks() {
Logger.log(.info, "Registering background tasks...")
let bgTaskIdentifier = "com.example.task"
BGTaskScheduler.shared.register(forTaskWithIdentifier: bgTaskIdentifier, using: DispatchQueue.main) { (task) in
Logger.log(.info, "Performing background task \(bgTaskIdentifier)")
Task.init {
if let updatedData = await appManager.getUpdateAppData() {
DispatchQueue.main.async {
appManager.data = updatedData
}
}
}
task.setTaskCompleted(success: true)
backgroundTaskManager.scheduleAppRefresh()
}
}
Hi there,
tl;dr: What's the best way to get all tracks (with catalog IDs) from a playlist that has more than 100 tracks, using MusicLibraryRequest.
I'm doing something dumb, not understanding something, and possibly both.
I've got an existing, kinda okay function that uses the MusicDataRequest and the Apple Music API to fetch all tracks from a playlist, with pagination like this:
func getTracksFromAppleMusicLibraryPlaylist(playlist: AppleMusicPlaylist) async throws -> [MusicKit.Track]? {
var tracksToReturn: [MusicKit.Track] = []
var libraryTracks: [AppleMusicLibraryTrack] = []
@Sendable
func fetchTracks(playlist: AppleMusicPlaylist, offset: Int) async -> AppleMusicPlaylistFetchResponse? {
do {
let playlistId = playlist.id
var playlistRequestURLComponents = URLComponents()
playlistRequestURLComponents.scheme = "https"
playlistRequestURLComponents.host = "api.music.apple.com"
playlistRequestURLComponents.path = "/v1/me/library/playlists/\(playlistId)/tracks"
playlistRequestURLComponents.queryItems = [
URLQueryItem(name: "include", value: "catalog"),
URLQueryItem(name: "limit", value: "100"),
URLQueryItem(name: "offset", value: String(offset)),
]
if let playlistRequestURL = playlistRequestURLComponents.url {
let playlistRequest = MusicDataRequest(urlRequest: URLRequest(url: playlistRequestURL))
let playlistResponse = try await playlistRequest.response()
let decoder = JSONDecoder()
// print("Get Tracks Dump")
// print(String(data: playlistResponse.data, encoding: .utf8)!)
let response = try decoder.decode(AppleMusicPlaylistFetchResponse.self, from: playlistResponse.data)
return response
} else {
print("Bad URL!")
}
} catch {
print(error)
}
return nil
}
Logger.log(.info, "Fetching inital tracks from \(playlist.attributes.name)")
if let response = await fetchTracks(playlist: playlist, offset: 0) {
if let items = response.data {
libraryTracks = items
}
if let totalItemCount = response.meta?.total {
Logger.log(.info, "There are \(totalItemCount) track(s) in \(playlist.attributes.name)")
if totalItemCount > 100 {
let remainingItems = (totalItemCount - 100)
let calls = remainingItems <= 100 ? 1 : (totalItemCount - 100) / 100
Logger.log(.info, "Total items: \(totalItemCount)")
Logger.log(.info, "Remaining items: \(remainingItems)")
Logger.log(.info, "Calls: \(calls)")
await withTaskGroup(of: [AppleMusicLibraryTrack]?.self) { group in
for offset in stride(from: 100, to: calls * 100, by: 100) {
Logger.log(.info, "Fetching additional tracks from \(playlist.attributes.name) with offset of \(offset)")
group.addTask {
if let response = await fetchTracks(playlist: playlist, offset: offset) {
if let items = response.data {
return items
}
}
return nil
}
}
for await (fetchedTracks) in group {
if let tracks = fetchedTracks {
libraryTracks.append(contentsOf: tracks)
}
}
}
}
}
}
// props to @JoeKun for this bit of magic
Logger.log(.info, "Matching library playlist tracks with catalog tracks...")
for (i, track) in libraryTracks.enumerated() {
if let correspondingCatalogTrack = track.relationships?.catalog?.first {
tracksToReturn.append(correspondingCatalogTrack)
print("\(i) => \(track.id) corresponds to catalog track with ID: \(correspondingCatalogTrack.id).")
} else {
Logger.log(.warning, "\(i) => \(track.id) doesn't have any corresponding catalog track.")
}
}
if tracksToReturn.count == 0 {
return nil
}
return tracksToReturn
}
While not the most elegant, it gets the job done, and it's kinda quick due to the use of withTaskGroup .esp with playlists containing more than 100 songs/tracks.
Regardless, I'm kinda stuck, trying to do something similar with the new MusicLibraryReqeust in iOS 16.
The only way I can think of to get tracks from a playlist, using MusicLibraryRequest, having read the new docs, is like this:
@available(iOS 16.0, *)
func getAllTracksFromHugePlaylist(id: MusicItemID) async throws -> [MusicKit.Track]? {
do {
var request = MusicLibraryRequest<MusicKit.Playlist>()
request.filter(matching: \.id, equalTo: id)
let response = try await request.response()
if response.items.count > 0 {
if let tracks = try await response.items[0].with(.tracks, preferredSource: .catalog).tracks {
Logger.log(.info, "Playlist track count: \(tracks.count)")
return tracks.compactMap{$0}
}
}
} catch {
Logger.log(.error, "Could not: \(error)")
}
return nil
}
The problem with this is that .with seems to be capped at 100 songs/tracks, and I can't see any way to change that.
Knowing that, I can't seem to tell MusicLibraryRequest that I want the tracks of the playlist with the initial request, where before I could use request.properties = .tracks, which I could then paginate if available.
Any help setting me on the right course would be greatly appreciated.
I'm trying to do something that I though would be simple; however, I'm tripping up on something...
In brief, I want to get all tracks from a playlist in an AppleMusic authorized user's playlist with the following function:
func getTracksFromAppleMusicPlaylist(playlistId: MusicItemID) async throws -> [Track]? {
print("Fetching AppleMusic Playlists...")
print("Playlist ID: \(playlistId)")
var playlistTracks: [Track]? = []
do {
var playlistRequest = MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: playlistId )
playlistRequest.properties = [.tracks]
let playlistResponse = try await playlistRequest.response()
print("Playlist Response: \(playlistResponse)")
let playlistWithTracks = playlistResponse.items
let tracks = playlistWithTracks.flatMap { playlist -> MusicItemCollection<Track> in
playlist.tracks ?? []
}
playlistTracks = tracks.count > 1 ? tracks : nil
} catch {
print("Error", error)
// handle error
}
return playlistTracks
}
This function results in the following error:
2021-08-28 04:25:14.335455+0700 App[90763:6707890] [DataRequesting] Failed to perform MusicDataRequest.Context(
url: https://api.music.apple.com/v1/catalog/us/playlists/p.7XxxsXxXXxX?include=tracks&omit%5Bresource%5D=autos,
currentRetryCounts: [.other: 1]
) with MusicDataRequest.Error(
status: 404,
code: 40400,
title: "Resource Not Found",
detailText: "Resource with requested id was not found",
id: "QMK7GH4U7ITPMUTTBKIOMXXXX",
originalResponse: MusicDataResponse(
data: 159 bytes,
urlResponse: <NSHTTPURLResponse: 0x00000002820c0b60>
)
).
The playlistID being used is a value that has been picked from an existing playlist in the user's library, via a function that uses this code snippet:
if let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists?limit=100") {
let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url))
...
The only thing I can think of is that the playlistId from the above snippet is converted to a string when decoding into a struct, after which it is changed back to a MusicItemID with an init, like MusicItemID(playlistId).
Any thoughts? Because I'm at a loss...
Hi there,
I have a related forum thread here and a Feedback Assistant ticket open, but this issue seems different.
Sometime within the last 2-3 weeks, code related to MusicLibrary has stopped working. None of my code has changed.
For example, the below two snippets used to work fine:
for track in newTracks {
try await MusicLibrary.shared.add(track, to: targetPlaylist)
}
try await MusicLibrary.shared.edit(targetPlaylist, items: items)
newTracks and items are both fetched using:
try await targetPlaylist.with(.tracks, preferredSource: .catalog).tracks
Using preferredSource: .catalog was a workaround used to address the issue in the aforementioned post above.
All iOS 16 capable functions are decorated with:
@available(iOS 16, *)
or in an if block:
if #available(iOS 16, *) {...
What's happening is that the following is showing up in the console:
2022-11-28 23:31:11.279648+0700 MyApp[38653:6736450] [core] Attempted to register account monitor for types client is not authorized to access: {(
"com.apple.account.iTunesStore"
)}
2022-11-28 23:31:11.279718+0700 MyApp[38653:6736450] [Default] <ICUserIdentityStoreACAccountBackend: 0x282adb520> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)"
2022-11-28 23:31:11.279758+0700 MyApp[38653:6736450] [Default] ICUserIdentity - Unable to retrieve DSID for userIdentity=<ICUserIdentity 0x2806eb120: [Active Account: <unresolved>]> - error=Error Domain=com.apple.accounts Code=7 "(null)"
These errors are not caught by a do/catch block, but I assume they are related to the issue, and I believe they have to do with MyApp trying to access things that Music Kit thinks it's not supposed to. For example, if MyApp attempts to work with a playlist that it did not create, errors would be expected, thrown errors.
The thing is that I know I'm working with resources that are created by MyApp.
In fact, in trying to test this, I just tried to create a playlist with the below, and the same behavior is occurring:
@available(iOS 16, *)
func createPlaylist2(name: String, description: String) async -> MusicKit.Playlist? {
do {
Logger.log(.info, "Creating Playlist: \(name)")
Logger.log(.shrug, "Does this work?")
let newPlaylist = try await MusicLibrary.shared.createPlaylist(name: name, description: description) // <= Things stop here!
Logger.log(.success, "New playlist created: \(newPlaylist)") // <= this isn't logged.
return newPlaylist // <= nothing is returned
} catch {
Logger.log(.error, "Could not create new playlist: \(error)") // <= no error logged.
}
return nil
}
The result is:
2022-11-29 00:15:01.875064+0700 MyApp[38794:6760471] [core] Attempted to register account monitor for types client is not authorized to access: {(
"com.apple.account.iTunesStore"
)}
2022-11-29 00:15:01.875372+0700 MyApp[38794:6760471] [Default] <ICUserIdentityStoreACAccountBackend: 0x283005720> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)"
2022-11-29 00:15:01.876677+0700 MyApp[38794:6760323] [EntityQuery] Finished executing query in 0.000999928s
2022-11-29 00:15:01.889055+0700 MyApp[38794:6760323] [EntityQuery] Finished fetching results in 0.0120001s
2022-11-29 00:15:01.891235+0700 MyApp[38794:6760329] [core] Attempted to register account monitor for types client is not authorized to access: {(
"com.apple.account.iTunesStore"
)}
2022-11-29 00:15:01.891684+0700 MyApp[38794:6760329] [Default] <ICUserIdentityStoreACAccountBackend: 0x283005720> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)"
📘 Creating Playlist: TEST PLAYLIST
🤷🏻♀️ Does this work?
2022-11-29 00:15:06.697374+0700 MyApp[38794:6760329] [] nw_path_necp_check_for_updates Failed to copy updated result (22)
What's really nasty is that errors are not thrown, so they can't be caught and handled in a catch block.
I know that iOS 16.1 got released around the end of October, but I really don't know what's going on here.
The behavior is showing up in both prod and when testing locally.
Any help would be most appreciated.
@JoeKhun: Did I miss the memo?
I've just begun to dip my toes into the iOS16 waters.
One of the first things that I've attempted is to edit a library playlist using:
try await MusicLibrary.shared.edit(targetPlaylist, items: tracksToAdd)
Where targetPlaylist is of type MusicItemCollection<MusicKit.Playlist>.Element and tracksToAdd is of type [Track]
The targetPlaylist was created, using new iOS16 way, here:
let newPlaylist = try await MusicLibrary.shared.createPlaylist(name: name, description: description)
tracksToAdd is derived by performing a MusicLibraryRequest on a specific playlist ID, and then doing something like this:
if let tracksToAdd = try await playlist.with(.tracks).tracks {
// add tracks to target playlist
}
My problem is that when I perform attempt the edit, I am faced with a rather sad looking crash.
libdispatch.dylib`dispatch_group_leave.cold.1:
0x10b43d62c <+0>: mov x8, #0x0
0x10b43d630 <+4>: stp x20, x21, [sp, #-0x10]!
0x10b43d634 <+8>: adrp x20, 6
0x10b43d638 <+12>: add x20, x20, #0xfbf ; "BUG IN CLIENT OF LIBDISPATCH: Unbalanced call to dispatch_group_leave()"
0x10b43d63c <+16>: adrp x21, 40
0x10b43d640 <+20>: add x21, x21, #0x260 ; gCRAnnotations
0x10b43d644 <+24>: str x20, [x21, #0x8]
0x10b43d648 <+28>: str x8, [x21, #0x38]
0x10b43d64c <+32>: ldp x20, x21, [sp], #0x10
-> 0x10b43d650 <+36>: brk #0x1
I assume that I must be doing something wrong, but I frankly have no idea how to troubleshoot this.
Any help would be most appreciated. Thanks. @david-apple?