swift3mpmediaquery

How to make an MPMediaQuery to return results based on releaseDate


I'm trying to create an MPMediaQuery that will return results in chronological order, preferably ascending or descending based on the query itself.

Right now my query returns items in ascending chrono order (oldest at top) but I'd like to be able to reverse the order. I need my results to be in an MPMediaQuery so that I can use it with the MPMediaPlayer.

var qryPodcasts = MPMediaQuery()
var titleFilter = MPMediaPropertyPredicate()
titleFilter = MPMediaPropertyPredicate(value: "This American Life", forProperty: MPMediaItemPropertyPodcastTitle, comparisonType: .equalTo)
qryPodcasts.addFilterPredicate(titleFilter)

EDIT::

I've been able to get a step closer to my goal however I still have a problem that causes a crash.

I've added this code which will sort the resulting query based on "releaseDate" however not all Podcasts conform so this property can be nil causing a crash:

let myItems = qryPodcasts.items?.sorted{($0.releaseDate)! > ($1.releaseDate)!}
let podCollection = MPMediaItemCollection(items: myItems!)
myMP.setQueue(with: podCollection!)

How can I avoid this error and how do I handle items without a releaseDate?


Solution

  • Just for this part: How can I avoid this error and how do I handle items without a releaseDate?

    Avoid using forced-unwrapping (!) and provide default values for nil:

    let myItems = qryPodcasts.items?.sorted{($0.releaseDate ?? Date.distantFuture) > ($1.releaseDate ?? Date.distantFuture)}
    

    You'd better check all other forced-unwrappings in your code, are you really 100% sure those never return nil?