2

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.

daihovey
  • 3,485
  • 13
  • 66
  • 110

2 Answers2

5

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.

  • This is all good - but then how do you know if its a track, album or artist? – daihovey Feb 07 '13 at 04:21
  • if you need this information then whats the problem not using 3 queries anyway? You could either use my solution and then in the for loop check those three values `if ([song.title isEqualToString:searchString]) {}` etc. OR if you use 3 queries and want to merge them you can check before adding a new element to your array with `if ([arr indexOfObject:@"new Item"] == NSNotFound) { //add new Item }` –  Feb 07 '13 at 13:59
  • the problem is performance. running 3 queries on the whole library can take seconds - where as Apple's music player does it very quickly. – daihovey Sep 18 '13 at 06:05
4

Try following code

 MPMediaQuery* query = [MPMediaQuery albumsQuery];

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

[query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:self.strTitle forProperty:MPMediaItemPropertyAlbumTitle]];
Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • This assumes the two strings are different. I want to be able to show, like the iPhone's iPod app's search table, the artist & or the album & or the track that is found. – daihovey Feb 06 '13 at 12:19