我正在开发一个
iOS app(swift)
,它为用户提供了一种更快的方式从他们的 Apple Music library
创建播放列表。阅读文档后,我仍然不知道如何访问用户库。
有没有办法可以访问用户库中的所有歌曲并将歌曲 ID 添加到
array
?
要访问 Apple 的音乐库,您需要将“隐私 - 媒体库使用说明”添加到您的 info.plist 中。然后您需要使您的类符合 MPMediaPickerControllerDelegate。要显示 Apple Music 库,您需要提供 MPMediaPickerController。要将歌曲添加到数组中,您可以实现 MPMediaPickerControllerDelegate 的 didPickMediaItems 方法。
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)
}
}