Skip to content

Displaying a Media Picker

Stanislav Osipov edited this page Apr 19, 2020 · 4 revisions

Let users choose the music they want to play by displaying a media picker interface from within your app.

Overview

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.

Importan: Your app's Info.plist file must include the NSAppleMusicUsageDescription key prior to accessing the user's music library. If that key is not present, displaying the media picker will cause your app to exit.

Adopt the Protocol and Create the System Music Player

To enable your app to respond to user input, adopt the ISN_IMPMediaPickerControllerDelegate protocol.

class MyMediaPickerDelegate : ISN_IMPMediaPickerControllerDelegate
{
    ...
}

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.

using SA.iOS.UIKit;
using SA.iOS.MediaPlayer;
...

var pickerController = new ISN_MPMediaPickerController();
pickerController.AllowsPickingMultipleItems = true;

if (ISN_UIDevice.CurrentDevice.UserInterfaceIdiom == ISN_UIUserInterfaceIdiom.IPad)
    pickerController.ModalPresentationStyle = ISN_UIModalPresentationStyle.Popover;

pickerController.SetDelegate(new MyMediaPickerDelegate());
pickerController.PresentViewController(true, () => {});

Implement the Protocol Methods

Implement two methods from the ISN_IMPMediaPickerControllerDelegate protocol: DidPickMediaItems and MediaPickerDidCancel. 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:

class MyMediaPickerDelegate : ISN_IMPMediaPickerControllerDelegate
{
    public void DidPickMediaItems(ISN_MPMediaPickerController mediaPicker, ISN_MPMediaItemCollection mediaItemCollection)
    {
        var musicPlayer = ISN_MPMusicPlayerController.SystemMusicPlayer;
        musicPlayer.SetQueueWithItemCollection(mediaItemCollection);
        musicPlayer.Play();

        mediaPicker.Dismiss(true, () => { });
    }

    public void MediaPickerDidCancel(ISN_MPMediaPickerController mediaPicker)
    {
        mediaPicker.Dismiss(true, () => { });
    }
}

About

Foundation

AV Foundation

App Tracking Transparency

Game Kit

Store Kit

UI Kit

Social

Replay Kit

Contacts

AVKit

Photos

App Delegate

User Notifications

MediaPlayer

Core Location

AdSupport

EventKit

CloudKit

Authentication Services

XCode

Knowledge Base

Clone this wiki locally