简体   繁体   中英

Launch a Swift OSX app by dragging and dropping a file or folder on it

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

First, select your project in Project Navigator (the root node) and goto the Info tab to declare the file types that your app supports. It can be as narrow as "only CSV files" or as wide as "any file and folder":

目标信息设置

Next, in your AppDelegate.swift file, add 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
    }
}

File types in OS X are determined by a hierarchy of Uniform Type Identifier (UTI). For example, a JPEG file has a UTI of public.jpeg , which is subbranch of public.image , which is a subbranch of public.data , etc. For more information, see Uniform Type Identifier Overview and System-Declared Uniform Type Identifiers .

To find out the UTI hierarchy of a file or folder, use mdls :

mdls -name kMDItemContentTypeTree /path/to/file_or_folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM