Article

Using Filters to Create Specialized Queries

Add a filter set to a query before populating a music player queue.

Overview

Creating a queue and adding it to a music player is a straightforward task. You populate the music player queue by creating a basic query and searching the user's music library for items that match the query. However, you can create filters and add them at query creation to refine the player's music queue. Filter for an album, artist, song, or any of a variety of other options. For a list of keys you can use as filters, see General Media Item Property Keys.

Create One or More Filters

You need to create a new filter for each item you want to filter on. For example, if you want to filter for a specific album and all songs that contain a certain word from that album, you need two separate filters.

let albumTitleFilter = MPMediaPropertyPredicate(value: "Album Title", forProperty: MPMediaItemPropertyAlbumTitle, comparisonType: MPMediaPredicateComparison.equalTo)
let songNameFilter = MPMediaPropertyPredicate(value: "Song Title", forProperty: MPMediaItemPropertyTitle, comparisonType: MPMediaPredicateComparison.contains)

Combine the Filters Into a Filter Set

The filters must be combined into a filter set before being assigned to a query.

let myFilterSet: Set<MPMediaPropertyPredicate> = [albumTitleFilter, songNameFilter]

Create a Query Using the Filter Set

Create a new query using the newly created filter set, and set the music player's queue.

let myQuery = MPMediaQuery(filterPredicates: myFilterSet)
myMusicPlayer.setQueue(with: myQuery)

See Also

Media Item Queries

MPMediaQuery

A query that specifies a set of media items from the device's media library by way of a filter and a grouping type.

MPMediaQuerySection

A range of media items or media item collections from within a media query.

MPMediaPropertyPredicate

A set of predicates that define a filter used in a media query.

MPMediaPredicate

An abstract class that defines classes for filtering media in a media query.