Setting default application for given file extension on Mac OS X from code

前端 未结 3 1658
旧巷少年郎
旧巷少年郎 2020-12-14 04:59

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

3条回答
  •  醉话见心
    2020-12-14 05:31

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

    #import 
    #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
    

提交回复
热议问题