How to populate a NSPopUpButton with the user's favorite folders
-
27-06-2021 - |
Question
I am new to programming for Mac, so forgive me if my question is too silly.
I am writing a small application, where I need to set a destination folder.
I think, instead of just using a NSButton
"Choose folder", the approach that Firefox or Safari with their "Save as..." dialogs take is a very user friendly one.
Using a NSPopUpButton
, where one can pick a folder from the user's favorites, or from the last used folders. Additionally I would add a top-most entry "Choose...", what would open a NSOpenPanel
.
My question is: How can I get the user's favorite folders, that are shown e.g. in the Finder application, and populate my NSPopUpButton
with them?
Here how it looks like in Firefox:
Solution
You can find the relevant functions inside the Application Services framework, and you can get the list of items like this:
LSSharedFileListRef favorites = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);
CFArrayRef snapshot = LSSharedFileListCopySnapshot(favorites, NULL);
CFIndex snapshotCount = CFArrayGetCount(snapshot);
for (CFIndex i = 0; i < snapshotCount; ++i) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(snapshot, i);
CFURLRef itemURL = NULL;
LSSharedFileListItemResolve(item, kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes, &itemURL, NULL);
NSLog(@"%@", itemURL);
if (itemURL != NULL) {
CFRelease(itemURL);
}
}
CFRelease(snapshot);
CFRelease(favorites);
When I run this on my computer, I get:
nwnode://domain-AirDrop
file://localhost/Applications/
file://localhost/System/Library/CoreServices/Finder.app/Contents/Resources/MyLibraries/myDocuments.cannedSearch/
file://localhost/Users/dave/
file://localhost/Users/dave/Desktop/
file://localhost/Users/dave/Developer/
file://localhost/Users/dave/Documents/
file://localhost/Users/dave/Downloads/
file://localhost/Users/dave/Dropbox/
Which corresponds to: