在代码中为Mac OS X上的给定文件扩展名设置默认应用程序 [英] Setting default application for given file extension on Mac OS X from code

查看:232
本文介绍了在代码中为Mac OS X上的给定文件扩展名设置默认应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有给定文件扩展名的应用程序列表(使用LSCopyApplicationURLsForURL)。我想从上述调用中选择一个应用程序时从代码更改默认文件关联。
有这样做吗?

I have the list of the applications for given file extension (using LSCopyApplicationURLsForURL). I want to change the default file association from code upon selecting one of the applications from the above call. Is there a way to do this?

推荐答案

这是一个非常相关的任务的代码片段:set自己作为给定文件扩展名的默认应用程序:

Here is a snippet of code for a very related task: set yourself as the default application for a given file extension:

#import <ApplicationServices/ApplicationServices.h>
#import "LaunchServicesWrapper.h"

@implementation LaunchServicesWrapper


+ (NSString *) UTIforFileExtension:(NSString *) extension {
    NSString * UTIString = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, 
                                                                       (CFStringRef)extension, 
                                                                       NULL);

    return [UTIString autorelease];
}

+ (BOOL) setMyselfAsDefaultApplicationForFileExtension:(NSString *) fileExtension {
    OSStatus returnStatus = LSSetDefaultRoleHandlerForContentType (
                                                                   (CFStringRef) [LaunchServicesWrapper UTIforFileExtension:fileExtension],
                                                                   kLSRolesAll,
                                                                   (CFStringRef) [[NSBundle mainBundle] bundleIdentifier]
                                                                   );

    if (returnStatus != 0) {
        NSLog(@"Got an error when setting default application - %d", returnStatus);
        // Please see the documentation or LSInfo.h

        return NO;
    }

    return YES;
}


@end

这篇关于在代码中为Mac OS X上的给定文件扩展名设置默认应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆