通过拖放文件或文件夹来启动 Swift OSX 应用程序

kma*_*_97 3 macos drag-and-drop swift

我试图弄清楚如何通过拖放文件或文件夹来在 OSX 上启动 Swift 应用程序,并将其视为所放资源的完整路径作为参数。

Cod*_*ent 5

首先,在 Project Navigator(根节点)中选择您的项目并转到 Info 选项卡以声明您的应用程序支持的文件类型。它可以像“仅 CSV 文件”一样窄,也可以像“任何文件和文件夹”一样宽:

目标信息设置

接下来,在您的AppDelegate.swift文件中,添加application(_:openFile:)

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func application(_ sender: NSApplication, openFile filename: String) -> Bool {
        print("openning file \(filename)")

        // You must determine if filename points to a file or folder

        // Now do your things...

        // Return true if your app opened the file successfully, false otherwise
        return true
    }
}
Run Code Online (Sandbox Code Playgroud)

OS X 中的文件类型由统一类型标识符 (UTI) 的层次结构确定。例如,JPEG 文件的 UTI 为public.jpeg,它是 的子分支public.image,它是 的子分支public.data等。有关更多信息,请参阅统一类型标识符概述系统声明的统一类型标识符

要找出文件或文件夹的 UTI 层次结构,请使用mdls

mdls -name kMDItemContentTypeTree /path/to/file_or_folder
Run Code Online (Sandbox Code Playgroud)