iosswiftmpmediaquery

iOS Query via Album MPMediaEntityPersistentID sometimes brings back no songs


I'm writing an app that plays music using Apple's built in MediaPlayer library. I store an array of albums and an array of Ids, and then when one is selected I search for an album using the id. For some reason, some of the albums can't find any songs despite having an id associated with them. It is the same albums each time that won't work, and there seems to be no pattern to this.

I use the following code to store the names and ids into two arrays

let query = MPMediaQuery.albumsQuery()
let mediaCollection = MPMediaItemCollection(items: query.items!)

for album in mediaCollection.items {
            albumTitleArray.append(album.albumTitle!)
            albumIdArray.append(album.albumPersistentID)
        }

When one is selected, I then pass the id to the queryMedia method

func queryMedia(identifier:MPMediaEntityPersistentID) -> MPMediaItemCollection {

    let predicateId = MPMediaPropertyPredicate(value: String(identifier), forProperty: MPMediaItemPropertyAlbumPersistentID, comparisonType:MPMediaPredicateComparison.EqualTo)

    let query = MPMediaQuery.init()
    query.addFilterPredicate(predicateId)

    let collection = MPMediaItemCollection(items: query.items!)

    return collection;
}

Any help in resolving this would be appreciated!


Solution

  • There must have been some characters being malformed, or a comparison error in the query caused by the conversion from MPMediaEntityPersistentID to String.

    I've changed the code to instead convert to a NSNumber and the query now finds all albums correctly.

    change this part in code example above

    String(identifier)
    

    to

    NSNumber(unsignedLongLong: identifier)
    

    so it looks like this

    func queryMedia(identifier:MPMediaEntityPersistentID) -> MPMediaItemCollection {
    
    let predicateId = MPMediaPropertyPredicate(value: NSNumber(unsignedLongLong: identifier), forProperty: MPMediaItemPropertyAlbumPersistentID, comparisonType:MPMediaPredicateComparison.EqualTo)
    
    let query = MPMediaQuery.init()
    query.addFilterPredicate(predicateId)
    
    let collection = MPMediaItemCollection(items: query.items!)
    
    return collection;
    }