swiftmpmediaitemcollection

Get song title from MPMediaItemCollection


I'm trying to rewrite my old player from Objective-C to Swift (by memory) and got in trouble. I've got array of songs like this

let query = MPMediaQuery.songsQuery()
query.groupingType = MPMediaGrouping.Title
songsArray = query.collections

Next in my table view I'm trying to get the name of each media item to put in the cell.textLabel. Like this:

var mediaItem = songsArray.objectAtIndex(indexPath.row)
var title = mediaItem.valueForProperty(MPMediaItemPropertyTitle)

But I'm not getting MPMediaItems, I'm getting the collection of items. So how can I take MPMediaItem from array of MPMediaItemCollections and get the title?


Solution

  • If you want to use the collection grouping of the media items and get information about the group of tracks within them, you can access a MPMediaItem representative of the contents of a collection through MPMediaItemCollection's representativeItem property.

    let collection = songsArray.objectAtIndex(indexPath.row) as! MPMediaItemCollection
    let representativeItem = collection.representativeItem
    let title = representativeItem.title
    

    Side note, if you'd rather deal with an array of MPMediaItems, you may want to consider using MPMediaQuery's items property rather than its collections property.