iPhone get all albums/artists

前端 未结 3 1957
说谎
说谎 2021-02-04 11:48

does any of you have example code (or a link to it) of how to retrieve all music albums or artist from the iPod media library?

Thanks in advance!

3条回答
  •  醉话见心
    2021-02-04 12:14

    Here you go. You can get the albums and their songs.

        /// Get all albums and their songs
    ///
    func getAllAlbums() {
        let query: MPMediaQuery = MPMediaQuery.albums()
        let allAlbums = query.collections
    
        allAlbumItems?.removeAll()
    
        guard allAlbums != nil else {
            return
        }
    
        for collection in allAlbums! {
            let item: MPMediaItem? = collection.representativeItem
    
            let albumName = item?.value(forKey: MPMediaItemPropertyAlbumTitle) as? String ?? ""
            let albumId = item!.value(forProperty: MPMediaItemPropertyAlbumPersistentID) as! NSNumber
            let artistName = item?.value(forKey: MPMediaItemPropertyArtist) as? String ?? ""
    
            let album = Album()
            album.name = albumName
            album.artistName = artistName
            album.albumId = String(describing: albumId)
            print("Album name: \(albumName)")
    
            // Get all songs in this album
            let mediaQuery = MPMediaQuery.songs()
            let predicate = MPMediaPropertyPredicate.init(value: albumId, forProperty: MPMediaItemPropertyAlbumPersistentID)
            mediaQuery.addFilterPredicate(predicate)
            let song = mediaQuery.items
    
            if let allSongs = song {
                var index = 0
    
                for item in allSongs {
                    let pathURL: URL? = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
                    if pathURL == nil {
                        print("@Warning!!! Track : \(item) is not playable.")
                    } else {
                        let trackInfo = SongItem()
                        trackInfo.index = index
                        trackInfo.mediaItem = item
    
                        let title = item.value(forProperty: MPMediaItemPropertyTitle) as? String ?? ""
                        let artistName = item.value(forProperty: MPMediaItemPropertyArtist) as? String ?? ""
                        trackInfo.songName = title
                        trackInfo.artistName = artistName
    
                        trackInfo.isSelected = false
                        trackInfo.songURL = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
                        album.songs?.append(trackInfo)
                        index += 1
                    }
                }
    
            }
    
            // Finally add the album object to albums array
            allAlbumItems?.append(album)
    
        }
    
    
        print("Total Album count: \(allAlbumItems?.count)")
    
    }
    

提交回复
热议问题