I'm working on an iOS app(swift)
that provides a faster way for users to create playlists from their Apple Music library
. After reading the documentation I still can't figure out how to get acces to the users library.
Is there a way I can get accesss to all the songs in the users library and add the song ids to an array
?
To access Apple's music library, you will need to add the "Privacy - Media Library Usage Description" to your info.plist. Then you need to make your class conform to MPMediaPickerControllerDelegate. To display the Apple Music library, you present the MPMediaPickerController. To add the songs to an array, you implement the didPickMediaItems method of MPMediaPickerControllerDelegate.
class MusicPicker:UIViewController, MPMediaPickerControllerDelegate {
//the songs the user will select
var selectedSongs: [URL]!
//this method is to display the music library.
func getSongs() {
var mediaPicker: MPMediaPickerController?
mediaPicker = MPMediaPickerController(mediaTypes: .music)
mediaPicker?.delegate = self
mediaPicker?.allowsPickingMultipleItems = true
mediaPicker?.showsCloudItems = false
//present the music library
present(mediaPicker!, animated: true, completion: nil)
}
//this is called when the user selects songs from the library
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
//these are the songs that were selected. We are looping over the choices
for mpMediaItem in mediaItemCollection.items {
//the song url, add it to an array
let songUrl = mpMediaItem.assetURL
selectedSongs.append(songURL)
}
//dismiss the Apple Music Library after the user has selected their songs
dismiss(animated: true, completion: nil)
}
//if the user clicks done or cancel, dismiss the Apple Music library
func mediaPickerDidCancel(mediaPicker: MPMediaPickerController) {
dismiss(animated: true, completion: nil)
}
}