启动OSX Finder窗口,选择特定文件

时间:2011-10-04 19:14:28

标签: objective-c macos applescript finder

我正在尝试以编程方式从Xcode项目启动OSX Finder窗口。我需要打开一个特定文件夹的窗口,并自动选择该文件夹中的特定文件。

有人知道如何在Objective c,applescript或Finder命令行参数中执行此操作吗?

谢谢!

8 个答案:

答案 0 :(得分:85)

Objective-C版本:

NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];

答案 1 :(得分:16)

$ open -R <path-to-reveal>

答案 2 :(得分:7)

另一种AppleScript风格 - Finder的揭示命令将打开包含文件夹的窗口并选择项目。如果有多个包含文件夹,将打开多个Finder窗口。

tell application "Finder" 
   to reveal {someAlias, "path/to/POSIXfile" as POSIX file, etc}

答案 3 :(得分:1)

我发现activateFileViewerSelectingURLs无法在Yosemite上运行(至少在与Finder分开的空间中)。它将导致切换到Finder的空间,但似乎不会选择URL。使用:

  • (BOOL)selectFile:(NSString *)fullPath inFileViewerRootedAtPath:(NSString *)rootFullPath

将从全屏应用切换空格并选择路径。

答案 4 :(得分:1)

Swift版本:

    let paths = ["/Users/peter/foo/bar.json"]
    let fileURLs = paths.map{ NSURL(fileURLWithPath: $0)}
    NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs(fileURLs)

答案 5 :(得分:1)

在 Finder 中显示多个文件

因为 open -R <path-to-reveal> 仅适用于单个文件。 我们可以改用 Apple Script。

从 user866649 的 answer,我们可以将其移植到 shell 脚本,如下所示:

osascript -e 'tell application "Finder" to reveal {"path/to/file1" as POSIX file, "path/to/file2" as POSIX file} activate'

刚刚创建了一个实用程序脚本:

finder.sh

#!/usr/bin/env bash

join() {
  local d=$1 s=$2
  shift 2 && printf %s "$s${@/#/$d}"
}

lst=()
for f in "$@"; do
  lst+=("\"$f\" as POSIX file")
done
files=$(join , "${lst[@]}")

osascript -e "tell application \"Finder\" to reveal {$files} activate"

那就试试吧:

chmod +x finder.sh
./finder.sh ~/Downloads ~/Desktop

它应该打开 Finder 并选择下载和桌面文件夹。

答案 6 :(得分:0)

path打开文件时:

NSString* path = @"/Users/user/Downloads/my file"
NSArray *fileURLs = [NSArray arrayWithObjects:[NSURL fileURLWithPath:path], nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];

答案 7 :(得分:0)

Swift 3.2 / 4.0版本: NSWorkspace.shared.activateFileViewerSelecting([outputFileURL])

相关问题