I encountered a question on StackOverflow today about how to add items to the favorites list in the Finder sidebar (which also appears in the standard Open and Save dialogs’ side bars). Though it’s already been answered before (I marked it as a duplicate, pointing to an answer from 2011), it appears the information is a bit outdated and contained no example code. I wrote, tested, and added the code to an updated answer. Not satisfied to stop there, I felt it would be easier to use if I created a simple category on
NSURL so you could tell a valid file URL directly to add itself to either the favorite items or favorite volumes list with one call. It’s compatible back to 10.5.
I wanted the design and usage to be simple, so I made a few drastic decisions:
- Due to some Finder bugs, you could set either a custom icon or a custom title for an item, but not both at the same time. Since the default behavior is to use the default icon and file name (sans extension, if one exists), I simply don’t provide the option to customize the icon or name.
- Though there’s an option to specify adding an item to the end, or to the beginning, or even to resolve each item and specify an item after which to add your own, this complicates matters, so I opted for append only. Your users may not appreciate you putting your item at the top of their lists anyway. Back of the line, new guy. ;-)
- The call either succeeds or fails. No complicated error messages, no nothing.
- Any valid file URL can be added by calling either
[url appendToFavoriteVolumesList];and checking the
BOOLreturn value if you care.
I hope you find it useful!