Search code examples
iosmpmusicplayercontrollermpmediaitemcollection

How to add MPMediaItem to MPMediaItemCollection


I hope to play MPMediaItemcollection using MPMusicPlayerController.

musicPlayer = [MPMusicPlayerController applicationMusicPlayer];

I have got the handler of MPMediaItem *mediaItem.

How can I add MPMediaItem to MPMediaItemCollection? I try addObject, but no function.


Solution

  • You can't add items to an already created MPMediaItemCollection. Instead you have to add them when you create the collection, using initWithItems: or collectionWithItems:.

    You could "fake" adding an item by creating a new collection based off of the old one. Something like this:

    NSMutableArray *items = [NSMutableArray arrayWithArray:myMediaItemCollection.items];
    [items addObject:myNewMediaItem];
    MPMediaItemCollection *myNewMediaItemCollection = [MPMediaItemCollection collectionWithItems:items];
    

    (If your collections are going to live beyond the scope of the current method, you'll need to assign them to properties or call retain as appropriate.)