使用Apple Music API创建播放列表?

时间:2017-01-18 04:49:53

标签: ios swift api

我正在使用iOS app(swift),为用户提供了一种更快捷的方式来创建来自Apple Music library的播放列表。阅读完文档之后,我仍然无法弄清楚如何访问用户库。

有没有办法可以访问用户库中的所有歌曲,并将歌曲ID添加到array

1 个答案:

答案 0 :(得分:1)

要访问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)
        }
   }