Swift - 按专辑排序艺术家查询

Swift - Sort artistsQuery By Album

我想像音乐应用一样按专辑对艺术家查询进行排序。我该怎么做?

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

此代码将创建一个可变数组。 artistsItemsSortedByAlbum.count 等于艺术家的数量,artistsItemsSortedByAlbum[index].count 等于专辑的数量。

         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!)
        }

实际上有一种更短的方法可以做到这一点。您可以为查询分配分组类型

artistQuery = MPMediaQuery.artistsQuery()
artistQuery.groupingType = MPMediaGrouping.AlbumArtist
artists = artistQuery.collections

至少我是这样做的