Hello i am trying to retrieve Artist with MPMediaQuery in iOS with following code.
In My ViewDidLenter code here
oad
MPMediaQuery *query = [MPMediaQuery artistsQuery];
self.arrayOfArtist = [query collections];
And In my cellForRowAtIndexPath
cell.textLabel.text = [NSString stringWithFormat:@"%@",[[self.arrayOfArtist objectAtIndex:indexPath.row] valueForProperty:MPMediaItemPropertyArtist]];
When i check with NSLog
, my arrayOfArtist
count is about 330.
However in my UITableView
, it's only show NULL
.
Is there anything i am wronging?
you should write:
cell.textLabel.text = [NSString stringWithFormat:@"%@",[[[self.arrayOfArtist objectAtIndex:indexPath.row] representativeItem] valueForProperty:MPMediaItemPropertyArtist]];
You can use the code to retrieve the artists and their songs.
/// Get all artists and their songs
///
func getAllArtists() {
let query: MPMediaQuery = MPMediaQuery.artists()
let allArtists = query.collections
allArtistItems?.removeAll()
guard allArtists != nil else {
return
}
for collection in allArtists! {
let item: MPMediaItem? = collection.representativeItem
let artistName = item?.value(forKey: MPMediaItemPropertyArtist) as? String ?? "<Unknown>"
let artistId = item!.value(forProperty: MPMediaItemPropertyArtistPersistentID) as! NSNumber
let artist = Artist()
artist.name = artistName
artist.artistId = String(describing: artistId)
print("Artist name: \(artistName)")
// Get all songs of this Artist
let mediaQuery = MPMediaQuery.songs()
let predicate = MPMediaPropertyPredicate.init(value: artistId, forProperty: MPMediaItemPropertyArtistPersistentID)
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 ?? "<Unknown>"
let artistName = item.value(forProperty: MPMediaItemPropertyArtist) as? String ?? "<Unknown>"
trackInfo.songName = title
trackInfo.artistName = artistName
trackInfo.isSelected = false
trackInfo.songURL = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
artist.songs?.append(trackInfo)
index += 1
}
}
}
// Finally add the album object to albums array
allArtistItems?.append(artist)
}
print("Total Artist count: \(allArtistItems?.count)")
}
You need to grab the artist property and then save it in the array. The valueForProperty method does not work correctly if your trying to use it on a standard array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With