objective-ccocoaitunesscripting-bridge

How do I retrieve an iTunes Track via ScriptingBridge?


I have two situations. Given a track id of a song, set the rating to some integer. The second is the same except I am given an array of track ids. I know I can use the ScriptingBridge to search for the iTunesTrack object based on a song's name, but is there some way to get it based off the track id? Something along the lines of:

iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
NSInteger *rating;
NSInteger *id;

if ( [iTunes isRunning] ) {
    iTunesTrack *track = [ iTunes trackForDatabaseID:id ];
    [ track setValue:rating forkey:@"rating" ];
}

For the second situation, is there a way to retrieve a SBElementArray object of iTunesTrack given an array of track ids? Something like:

iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
NSArray *ids; //array of NSIntegers

if ( [iTunes isRunning] ) {
    SBElementArray *tracks = [ iTunes tracksForDatabaseIDs:ids ];
    [ tracks setValue:rating forkey:@"rating" ];
}

I believe this would be more efficient than iteratively searching the library based on a song's name.


Solution

  • I just did this recently. Something like this should work for you. You need to ask the library playlist (named libraryPlaylist in this example) and not the application.

    NSArray *trackIDs = blah; // the ids you're searching for
    NSString *searchFilter = @"databaseID == %@";
    NSMutableArray *filters = [NSMutableArray arrayWithCapacity:[trackIDs count]];
    for (int i = 0; i < [trackIDs count]; i++) {
        [filters addObject:searchFilter];
    }
    searchFilter = [filters componentsJoinedByString:@" OR "];
    NSArray *trackResult = [[libraryPlaylist tracks] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:searchFilter argumentArray:trackIDs]];
    

    And that works just fine if the trackIDs array only contains a single item, so there's no need to write special code for that case.