objective-cmpmediaqueryitunes-sdkapple-musicmpmedialibrary

Apple Music API - Create a Playlist


I have been exploring the Apple Music API to see what kind of functionality I can expect to be able to use in an iOS app. I have created a little test app that gains permission from the user and outputs the playlists I have (and songs) to NSLog.

MPMediaQuery *myPlaylistsQuery = [MPMediaQuery playlistsQuery];
            [myPlaylistsQuery setGroupingType:MPMediaGroupingPlaylist];
            NSArray *playlists = [myPlaylistsQuery collections];
            
            for (MPMediaPlaylist *playlist in playlists) {
                NSLog (@"%@", [playlist valueForProperty: MPMediaPlaylistPropertyName]);
                
                NSArray *songs = [playlist items];
                
                for (MPMediaItem *song in songs) {
                    NSString *songTitle =
                    [song valueForProperty: MPMediaItemPropertyTitle];
                    NSLog (@"\t\t%@", songTitle);
                }
            }

From this, I have been able to deduce the following (but I'm not 100% certain):

So far, so good. What I want to know is:

I know there is an MPMediaPlaylist addItem and add method but can't seem to find a way of creating the new playlist itself.

According to this page it should be possible: https://affiliate.itunes.apple.com/resources/blog/apple-music-api-faq/

Can a developer create brand new playlists on the user’s device with the Apple Music API?

Yes. The API allows develops to new create playlists on the user’s device.


Solution

  • I've figured this out. If you use the following code you can generate a new playlist and perform an action on it.

    NSUUID *uuid = [NSUUID UUID]; //uuid for the playlist
    [[MPMediaLibrary defaultMediaLibrary] getPlaylistWithUUID:uuid creationMetadata:[[MPMediaPlaylistCreationMetadata alloc] initWithName:@"YOUR PLAYLIST NAME"] completionHandler:^(MPMediaPlaylist * _Nullable playlist, NSError * _Nullable error) {
        NSLog(@"%@", error);
    
        if (!error) {
            NSLog(@"All ok let's do some stuff with the playlist!"); 
        }
    }];
    

    Apple's documentation on the whole API is severely lacking in terms of sample code and practical examples!