Cocoa/Obj-C - Open file when dragging it to application icon

扶醉桌前 提交于 2019-12-03 01:32:10

First add the proper extensions to CFBundleDocumentTypes inside the .plist file.

Next implement the following delegates:
- application:openFile: (one file dropped)
- application:openFiles: (multiple files dropped)

Reference:
NSApplicationDelegate Protocol Reference

Response to comment:

Step by step example, hopefully it makes everything clear :)

Add to the .plist file:

 <key>CFBundleDocumentTypes</key>
        <array>
            <dict>
                <key>CFBundleTypeExtensions</key>
                <array>
                    <string>xml</string>
                </array>
                <key>CFBundleTypeIconFile</key>
                <string>application.icns</string>
                <key>CFBundleTypeMIMETypes</key>
                <array>
                    <string>text/xml</string>
                </array>
                <key>CFBundleTypeName</key>
                <string>XML File</string>
                <key>CFBundleTypeRole</key>
                <string>Viewer</string>
                <key>LSIsAppleDefaultForType</key>
                <true/>
            </dict>
        </array>

Add to ...AppDelegate.h

- (BOOL)processFile:(NSString *)file;
- (IBAction)openFileManually:(id)sender;

Add to ...AppDelegate.m

- (IBAction)openFileManually:(id)sender;
{
    NSOpenPanel *openPanel  = [NSOpenPanel openPanel];
    NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil];
    NSInteger result  = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
    if(result == NSOKButton){
        [self processFile:[openPanel filename]];
    }
}

- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
    return [self processFile:filename];
}

- (BOOL)processFile:(NSString *)file
{
    NSLog(@"The following file has been dropped or selected: %@",file);
    // Process file here
    return  YES; // Return YES when file processed succesfull, else return NO.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!