开发者

Application selection - Cocoa

I want to display a dialog which allows the user to browse through their current applicat开发者_JAVA技巧ions (/Applications) and I need to get the full path of that application (selected). How would I go about this? Code samples are appreciated.

Thanks.


Something like this would be a good start:

NSArray *appsDirs = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, 
                       NSLocalDomainMask,  YES);
NSString *appsDir = nil;
if ([appsDirs count]) appsDir = [appsDirs objectAtIndex:0];

NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setTitle:NSLocalizedString(@"Add Application", @"")];
[openPanel setMessage:NSLocalizedString(@"Choose the application to add.", @"")];
[openPanel setPrompt:NSLocalizedString(@"Add Application", @"")];
[openPanel setAllowsMultipleSelection:YES]; // ?
[openPanel setCanChooseDirectories:NO];
[openPanel setDelegate:self];

NSInteger result = [openPanel runModalForDirectory:appsDir
                                              file:nil
                                             types:
                    [NSArray arrayWithObject:NSFileTypeForHFSTypeCode('APPL')]];

if (result == NSOKButton) {
    NSArray *fileURLs = [openPanel URLs];
    for (NSURL *URL in fileURLs) {
         NSString *path = [URL path];
         // add path, etc.
    }
}


See Apple's Application File Management guide, which shows how to use the NSOpenPanel class.


There are several mechanisms that you can use to do this. One is to use an open file dialog as suggested in the other answers.

Another, if you know the type of file that you want to locate suitable apps for, is to use one of these Launch Services functions:

  • LSCopyApplicationURLsForURL(), which returns a list of apps that can open a particular URL
  • LSCopyAllHandlersForURLScheme(), which returns a list of apps that can open a particular URL scheme (e.g. http)
  • LSCopyAllRoleHandlersForContentType(), which returns a list of apps that handle a particular type of content

Alternatively, you can use Spotlight to locate all the applications on your system and display a dialog that allows you to select from them.

However, bear in mind that by default this will return a lot of apps, including helper apps (on my system it returns 1628 results), so you would need to be judicious in creating the search predicate and restrict your search to the Applications folders only and exclude files inside bundles and system locations.

Below is some code that will find all apps on the system. You will need to modify the predicate for your own use.

#import <Cocoa/Cocoa.h>
@interface Search : NSObject
{
    NSMetaDataQuery* query;
}
@end


@implementation Search
-(id) init
{
    self = [super init];
    if(self)
    {
        query=[[NSMetadataQuery alloc] init];
        [query setPredicate:[NSPredicate predicateWithFormat:@"kMDItemKind == \"Application\""]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedSearchForApplications:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
        [query startQuery];
    }
    return self;
}

-(void) finishedSearchForApplications:(NSNotification*) notification
{
    //get the number of items in the results
    NSUInteger resultCount = [[query results] count];
    NSMutableArray* appsFound = [NSMutableArray array];

    //loop through the results and add their paths to an array
    NSUInteger i;
    for(i=0;i<resultCount;i++)
    {
        id queryResult=[query resultAtIndex:i];
        NSString* pathOfItem = [[[[queryResult valueForKey:@"kMDItemPath"] stringByStandardizingPath] stringByAbbreviatingWithTildeInPath] stringByDeletingPathExtension];
        NSDictionary* fileInfo = [NSDictionary dictionaryWithObject:pathOfItem forKey:@"path"];
        [appsFound addObject:fileInfo];
    }
    NSLog(@"%ld apps found: %@",resultCount,appsFound);
    //do something with appsFound
}

- (void)dealloc
{
    [query release];
    [super dealloc];
}
@end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜