How to open any file you drag onto your app’s dock icon

One of the most important aspects of the OS X interface paradigm is drag and drop. One of the best places to support drag and drop is on your dock icon, because it is always available no matter where you’re dragging from. It won’t be hidden behind a window or lost on some other space.

So how do you make it so that your app will accept files dragged onto it’s dock icon (aka dock tile)? It’s pretty easy. You’re just going to add something to your apps info.plist.

The key you’ll add is called CFBundleDocumentTypes. Then you’ll add information about the types of files you want to support. Maybe you want to open just image or just text files. Lots of this functionality should be automatically built in to your app if it is document based.

You can do this a slightly prettier way in Xcode 4 by looking at the info tab of your app target’s properties page.

Using * as the extension will let your app accept any type of file on it’s dock icon. Setting the role to Viewer tells the OS that you are only going to look at the files, not modify them.

So now your app’s dock icon should highlight when a file is dragged onto it. What now? In your appDelegate you’re going to implement any of NSApplications open methods. The two that you might find most useful are these.

-(BOOL)application:(NSApplication *)sender openFile:(NSString *)filename
{
   NSLog(@"%@", filename);
}

-(BOOL)application:(NSApplication *)sender openFiles:(NSArray *)filenames
{
   NSLog(@"%@", filenames);
   YES;
}

So that’s it. Once you implement those methods in your application’s delegate, you’ll be able to handle opening files from your dock icon. More information about NSApplicationDelegate can be found here.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>