os x 代码方式添加文件夹到Finder收藏栏中

来源:互联网 发布:深证指数收盘价数据 编辑:程序博客网 时间:2024/06/14 09:49

手动的方式

直接拖拽文件夹到Finder左侧栏的收藏栏中就可以了

代码方式

使用 LSSharedFileList 函数添加,使用的是CoreService framework,需要引入#import CoreServices/CoreServices.h

- (IBAction)btnAction:(id)sender {    // 例如桌面上有aa bb cc dd 四个文件夹    NSArray *pathArr = @[@"/Users/lan/Desktop/aa" , @"/Users/lan/Desktop/bb", @"/Users/lan/Desktop/cc", @"/Users/lan/Desktop/dd"];    // 在当前用户home 目录下创建 sidebar 隐藏文件夹,再在隐藏文件夹下创建 sidebarTest 文件夹    NSString *homePath = NSHomeDirectory();    NSString *faPath = [homePath stringByAppendingPathComponent:@".sidebar/sidebarTest"];    NSFileManager *manager = [NSFileManager defaultManager];    NSError *erro;    if([manager createDirectoryAtPath:faPath withIntermediateDirectories:YES attributes:nil error:&erro]) {        if (erro) {            NSLog(@"create direct error %@", erro);            return;        }    };    // 创建符号链接到 sidebarTest 目录下    NSString *pathName = nil;    for (NSString *path in pathArr) {        pathName = [path lastPathComponent];        [manager createSymbolicLinkAtPath:[faPath stringByAppendingPathComponent:pathName] withDestinationPath:path error:nil];    }    // 把 sidebarTest 文件加添加到 Finder 侧栏的收藏栏中    LSSharedFileListRef sflRef = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);    if (!sflRef) return;    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:faPath];    LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(sflRef, kLSSharedFileListItemBeforeFirst, NULL, NULL, url, NULL, NULL);    CFRelease(sflRef);    CFRelease(item);}

注意

LSSharedFileListItemRef 等方法在10.11后已经不赞成使用了,你可以尝试使用 Finder 插件,或者你有更好的方法请告诉我。

0 0