3

It looks to me like MusicKit is only available on beta iOS versions. I'm pretty sure, however, I've seen a way to do it before without using MusicKit. Is this possible? I've been searching around for a while now and I've only found things about MusicKit.

I know it's possible on macOS — can I use the same API?

EDIT: All I need to do it get a list of the user's songs/albums. I don't need any functionality to play the songs.

Zac
  • 813
  • 10
  • 22

2 Answers2

6

Since iOS 3.0, and it's not deprecated, you can use MPMediaQuery class to access user library. This allows you to get objects such as albums, artists, audiobooks, playlists, songs, etc.

let myPlaylistQuery = MPMediaQuery.playlists()
let playlists = myPlaylistQuery.collections
for playlist in playlists! {
    print(playlist.value(forProperty: MPMediaPlaylistPropertyName)!)

    let songs = playlist.items
    for song in songs {
        let songTitle = song.value(forProperty: MPMediaItemPropertyTitle)
        print("\t\t", songTitle!)
    }
}

source

Remember that since iOS 10 you have to ask user for permission to access Music library. You need to add Privacy - Media Library Usage Description to Info.plist file. Without this, app will crash when requesting authorization.

For requesting access, use MPMediaLibrary class and its requestAuthorization method

lvp
  • 2,078
  • 18
  • 24
3

You can get list of songs using MPMediaLibrary like this

for song in MPMediaQuery.songs().items! {
    print(song.persistentID.description)
    print(song.title!)
    print(song.assetURL?.absoluteString ?? "")
    print(song.albumTitle ?? "Unknown")
    ...
}
MrGreen
  • 479
  • 4
  • 24