Let users choose the music they want to play by displaying a media picker interface from within your app.
- Media Player
Adding a media-picker view controller to your app allows users to choose music items from their Apple Music library without leaving your app. You can configure the media picker to accept single or multiple items from the user.
Adopt the Protocol, and Create the System Music Player
To enable your app to respond to user input, adopt the
MPMedia protocol, and create a global instance of the music player.
Add the Media-Picker View Controller
Set the media-picker view controller as a popover presentation controller when you target an iPad. Set the source view and delegate, and present the media picker. In this example, the media picker allows the user to select multiple items, and the source view is a
Add a Select Music Button, and Target the Previously Created Function
To create a button that gives the user access to their Apple Music library from within your app:
UIButtonobject, and name it Select Music.
Attach restraints to center the button in the display.
Control-drag from the new button object to View Controller in the Outline view, and select
choosefrom the menu that appears.
Songs Button Pressed:
The Select Music button is the source view for the media-picker view controller, which is presented modally. It displays the user's Apple Music library, allowing them to choose the music they wish to play.
Implement the Protocol Methods
Implement two methods from the
media. Inside these methods, add code to handle the user's choice of items to create a music queue, and code to dismiss the view controller. The following code shows how to set the music player queue, begin playing the user's choices, and dismiss the view controller if the user doesn't choose any media items: