Im using this code to select tracks
//open the media picker, allow the inport of any type of audio
MPMediaPickerController *mediaPickerController = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAnyAudio];
mediaPickerController.prompt = @"Choose items to import";
//we want to be able to import multiple items at once
mediaPickerController.allowsPickingMultipleItems = YES;
mediaPickerController.delegate = self;
When choosing the items in the MPMediaPickerController
I have noticed that pressing on the same item twice adds it to the MPMediaItemCollection
twice. As I am importing tracks into my app I end up importing them twice.
I would like a way to specify that the track only gets added once or, failing that, the ability to filter out duplicate tracks from the selection. If this is this possible how would I go about doing it?
I am targeting iOS5.
I ran into this problem a while back, and unfortunately, without remaking the picker from the ground up (do-able) there is no way of specifying whether or not to allow duplicates. However, it is relatively painless to check for and remove duplicates after selection.
There are a couple of options as outlined below, but the difference really boils down to whether or not you wish to preserve the order that the collection was originally in.
The first basically just loops through the items in the collection and if a secondary array doesn't contain that object, it copies it out. The second copies all objects from the collection into a NSSet which will strip all duplicates, and then copies back. This solution does not preserve order at all.
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
MPMediaItemCollection *dupeFreeCollection = nil;
if (shouldPreserveOrder) {
//Will preserve order, with exception of subtracted duplicates
NSMutableArray *newCopy = [NSMutableArray new];
for (MPMediaItem *item in mediaItemCollection.items) {
if (![newCopy containsObject:(MPMediaItem *)item]) {
[newCopy addObject:(MPMediaItem *)item];
}
}
dupeFreeCollection = [[MPMediaItemCollection alloc] initWithItems:newCopy];
}else{
//Will not preserve order
NSSet *set = [[NSSet alloc] initWithArray:mediaItemCollection.items];
dupeFreeCollection = [[MPMediaItemCollection alloc] initWithItems:[set allObjects]];
}
}
Keep in mind, the code I've included is untested because I can't seem to find an iPhone cable, but it should be enough to get you going.