2011/05/30

Checking if MPMediaItem exists by URL

If you are usings AVPlayer with Asset URLs, you might want to check asset's existence on the device.
If the asset is a file in local folder - no problem, you can use NSFileManager to check for existance? But what if it's inside the iPod library? The following trick wasn't easy to find, but here it is:

   NSURL* furl = [f trackUrl];
//        ipod-library://item/item.mp3?id=
        if([[furl scheme] isEqualToString:@"ipod-library"]){
            NSNumber* pid = [NSNumber numberWithLongLong: [[f.name substringFromIndex:32] longLongValue] ];;
            MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:pid forProperty:MPMediaItemPropertyPersistentID];
            MPMediaQuery *songQuery = [[[MPMediaQuery alloc] init] autorelease];
            [songQuery addFilterPredicate: predicate];
            if (songQuery.items.count == 0) {
                return NO; // NOT FOUND!
            }

5 comments:

  1. This is great!
    Quick question, what would be the return of "f.name" in the line 'NSNumber* pid = [NSNumber...'?

    Is it the song name? or something else? I'm just not sure what class type 'f' is.

    Thanks again.

    ReplyDelete
  2. f is media library asset. 'name' will return it's encoded name - usually a 'persistent ID'

    ReplyDelete
  3. this is another way to get the pid:
    pid = [f valueForKey:MPMediaItemPropertyPersistentID];

    ReplyDelete
  4. that's correct, but the issue was to find PID from a URL, without having the actual asset

    ReplyDelete
  5. You just saved my day :) thank you, hope good karma shines your way...

    ReplyDelete