Possible to query for song by Apple Music trackId?

Given an Apple Music trackId is it possible to query the user’s media library to see if they’ve added it to their library? Something like:

Code Block
let predicate = MPMediaPropertyPredicate(value: "1440818675", forProperty: MPMediaItemPropertyPersistentID)
let query = MPMediaQuery(filterPredicates: Set([predicate]))
let songs = query.items
let isInLibrary = !songs.isEmpty

Replies

Did you ever figure this out? I'm looking for the same thing.

Hello @Jordan and @cheddarburrito,

MediaPlayer exposes another property you could filter by which works for IDs of Apple Music subscription items: MPMediaItemPropertyPlaybackStoreID.

Could you try something like this?

let predicate = MPMediaPropertyPredicate(value: "1440818675", forProperty: MPMediaItemPropertyPlaybackStoreID)
let query = MPMediaQuery(filterPredicates: Set([predicate]))
let songs = query.items
let isInLibrary = !songs.isEmpty

I hope this helps.

Best regards,

  • Hi @JoeKun! I tried this out but the app crashes with exception: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'MPMediaPropertyPredicate cannot filter using the playbackStoreID property.'

  • Hello @Jordan,

    I apologize for the incorrect guidance about using MPMediaItemPropertyPlaybackStoreID for this specific use case. You're correct, this property is indeed not designed to be used in a predicate.

    We'll get back to you in a few days with an alternative suggestion on how to check if an Apple Music track is already present in the user's library.

    Best regards,

Add a Comment

Hello @Jordan and @cheddarburrito,

I have a new suggestion which could help you achieve what you're trying to do. Using Apple Music API directly, you could request the library relationship on something like a song. See the list of song relationships for more information.

The idea is that if the resulting SongsLibraryRelationship is not empty, and contains one library song, then you know that the user has this song in their music library.

I hope this helps.

Best regards,

  • Thanks @JoeKun, that's an interesting approach. Looks like there's a new native SDK that may be able to accomplish the same thing as the Web SDK you've linked to? Would you happen to have any sample/pseudo code to demonstrate the idea? Thanks!

  • Hello @Jordan,

    Actually, I would recommend you request an appointment with one of us at our MusicKit for Swift Labs at WWDC. We have a lab tomorrow (whose registration window is about to close) and another lab on Thursday, for which you have more time to register.

    That's probably going to be the most efficient way for us to provide you with specific suggestions on how to achieve this.

    I hope this helps.

    Best regards,

Add a Comment