【问题标题】:How do I programmatically open a folder in the Finder without selecting anything?如何在不选择任何内容的情况下以编程方式在 Finder 中打开文件夹?
【发布时间】:2016-03-04 22:29:36
【问题描述】:

当用户单击我的应用程序中的按钮时,我希望 Finder 出现在前面并显示文件夹的内容。 NSWorkspace 类有两个调用,activateFileViewerSelectingURLs(:)selectFile(:inFileViewerRootedAtPath:),几乎可以满足我的要求,但它们都选择一个或多个项目。我不希望 Finder 选择任何东西。

如果我进入,我会看到我想要的行为

/usr/bin/open /path/to/my/folder

在终端中。是否有 Cocoa API 可以执行此操作,还是我需要让 NSTask 运行 /usr/bin/open

【问题讨论】:

    标签: macos cocoa


    【解决方案1】:

    要求工作区将文件夹作为文件打开就足够了,因为 Finder 是文件夹的默认应用程序。例如:

    NSWorkspace.shared.open(
        URL(
            fileURLWithPath: "/System/Library/CoreServices",
            isDirectory: true
        )
    )
    

    isDirectory 参数是可选的,但传递它会保存系统调用。)

    【讨论】:

    • 请注意 openFile(_) 现在已弃用。
    【解决方案2】:

    如果您想确保无论默认应用设置如何都让 Finder 打开文件夹,您可以使用 Applescript:

    NSString *script = [NSString StringWithFormat: 
        @“tell application \”Finder\”\nopen folder (\“%@\” as POSIX file)\nend tell\n”, path];
    
    NSAppleScript *openScript = [[NSAppleScript alloc] initWithSource: script];
    [openScript executeAndReturnError:nil];
    

    【讨论】:

    • 很好的 AppleScript 破解!
    • 无论有没有标签,似乎都无法让它继续工作。
    【解决方案3】:

    AppleScript 对我来说是一个解决方案,但我必须添加标签 (\t) 才能让它工作:

    NSString* path = ...;
    NSString* script = [NSString stringWithFormat:@"tell application \"Finder\"\n\tactivate\n\tmake new Finder window to (POSIX file \"%@\")\nend tell\n", path];
    NSAppleScript* openScript = [[NSAppleScript alloc] initWithSource:script];
    [openScript executeAndReturnError:nil];
    

    因此生成的脚本如下所示:

    tell application "Finder"
        activate
        make new Finder window to (POSIX file "/Users/MyUser/someFolder")
    end tell
    

    【讨论】:

      【解决方案4】:
      NSWorkspace.shared.open(URL(fileURLWithPath: "/your/path/goes/here"))
      

      请注意,您必须对要打开的路径具有读取权限。

      【讨论】:

        猜你喜欢
        • 2017-10-19
        • 1970-01-01
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        • 2021-08-23
        • 2015-08-06
        • 1970-01-01
        相关资源
        最近更新 更多