Search code examples
swift2mpmediaquery

Swift - Sort artistsQuery By Album


I want to sort the artists query by album like the Music app. How can I do that?

var artistsQuery = MPMediaQuery.artistsQuery()
var artistsQuery.groupingType = MPMediaGrouping.AlbumArtist
var songsByArtist = artistsQuery.collections

Solution

  • This code will create a mutable array. The artistsItemsSortedByAlbum.count equals the amount of artists & the artistsItemsSortedByAlbum[index].count equals the amount of albums.

             var artistsItemsSortedByAlbum = NSMutableArray()
    
             for var i = 0; i < artists.count; i++ {
                let collection:MPMediaItemCollection = artists[i] as! MPMediaItemCollection
                let rowItem = collection.representativeItem!
    
                let albumsQuery = MPMediaQuery.albumsQuery()
                let albumPredicate:MPMediaPropertyPredicate = MPMediaPropertyPredicate(value: rowItem.valueForProperty((MPMediaItemPropertyAlbumArtist)), forProperty: MPMediaItemPropertyAlbumArtist)
                albumsQuery.addFilterPredicate(albumPredicate)
    
                let artistAlbums = albumsQuery.collections
                artistsItemsSortedByAlbum.addObject(artistAlbums!)
            }