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

时间:2017-01-22 22:15:40

标签: swift macos drag-and-drop

我试图找出如何通过拖放文件或文件夹在OSX上启动Swift应用程序,让它将丢弃的资源的完整路径视为参数。

1 个答案:

答案 0 :(得分:2)

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

enter image description here

接下来,在您的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 openned the file successfully.
        return true
    }
}

OS X中的文件类型由统一类型标识符(UTI)的层次结构确定。例如,JPEG文件的UTI为public.jpeg。它是public.image的子分支,是public.data的子分支,等等。有关详细信息,请参阅Uniform Type Identifier OverviewSystem-Declared Uniform Type Identifiers

要查找文件的UTI层次结构,请使用mdls

mdls -name kMDItemContentTypeTree /path/to/myFile.ext
相关问题