Get Path to selected file in Finder

前端 未结 2 1101
别跟我提以往
别跟我提以往 2021-02-02 04:26

How would I retrieve an array of paths to the selected files in Finder?

I have searched around but have only found links regarding AppleScript. I have also looked at

相关标签:
2条回答
  • 2021-02-02 05:05

    If it is possible to get the list of selected files in a given Finder window using AppleScript, you can probably use Scripting Bridge in a Cocoa application to interface with Finder. Quoting Apple’s documentation,

    Scripting Bridge is a framework and a technology that makes it much easier for Cocoa developers to control and communicate with scriptable applications. Instead of incorporating AppleScript scripts in your application or dealing with the complexities of sending and handling Apple events, you can simply send Objective-C messages to an object that represents an application with a scripting interface. Your Cocoa application can do anything an AppleScript script can, but it does so in Objective-C code that is integrated with the rest of your project’s code.

    There is no Cocoa class that represents Finder or, more specifically, Finder windows. Finder is an application, and a scriptable application at that, so Scripting Bridge is the way to go.

    0 讨论(0)
  • 2021-02-02 05:21

    Expanding on @Bavarious's (correct) answer, here's how I've gotten the selection from Finder using the Scripting Bridge:

    #import "Finder.h" //my copy is here: https://github.com/davedelong/BetterInfo/blob/master/Finder.h
    
    FinderApplication * finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.finder"];
    SBElementArray * selection = [[finder selection] get];
    
    NSArray * items = [selection arrayByApplyingSelector:@selector(URL)];
    for (NSString * item in items) {
        NSURL * url = [NSURL URLWithString:item];
        NSLog(@"selected item url: %@", url);
    }
    
    0 讨论(0)
提交回复
热议问题