daihovey
daihovey

Reputation: 3575

Search for multiple types with MPMediaPropertyPredicate

I have the following:

MPMediaPropertyPredicate *titlePredicate = [MPMediaPropertyPredicate predicateWithValue:textString 
                                                                            forProperty:MPMediaItemPropertyTitle
                                                                         comparisonType:MPMediaPredicateComparisonContains];

NSSet *predicateSet = [NSSet setWithObject:titlePredicate];
MPMediaQuery *searchQuery = [[MPMediaQuery alloc] initWithFilterPredicates:predicateSet];
NSArray *itemsFromTextQuery = [searchQuery items];

 for (MPMediaItem *song in itemsFromTextQuery) 
 {
     [arrayOfSongItems addObject:song];
 }

Which works great, but only searched the Title of the track. I'd like it to return results for the Title, the Artist and the Album name.

Upvotes: 2

Views: 1798

Answers (2)

user207616
user207616

Reputation:

this works for me:

MPMediaQuery *searchQuery = [[MPMediaQuery alloc] init];
NSPredicate *test = [NSPredicate predicateWithFormat:@"title contains[cd] %@ OR albumTitle contains[cd] %@ OR artist contains[cd] %@", searchString, searchString, searchString];
NSArray *filteredArray = [[searchQuery items] filteredArrayUsingPredicate:test];

//NSLog(@"%@", [filteredArray valueForKeyPath:@"title"]);

for (MPMediaItem *song in filteredArray) 
{
    [arrayOfSongItems addObject:song];
}

I basically filter after getting all items from media query. I don't think my solution is better than filtering the query at the first place, but definitely better than searching three times separately. Or iterating through the array multiple times.

Upvotes: 5

Kuntal Gajjar
Kuntal Gajjar

Reputation: 59

Try following code

 MPMediaQuery* query = [MPMediaQuery albumsQuery];

[query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:self.strArtist forProperty:MPMediaItemPropertyArtist]]

[query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:self.strTitle forProperty:MPMediaItemPropertyAlbumTitle]];

Upvotes: 4

Related Questions