Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 497
bela.bartha Avatar asked Jul 27 '10 13:07

bela.bartha


2 Answers

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
like image 155
Guillaume Avatar answered Nov 17 '22 01:11

Guillaume


Here’s a slightly modified and ARC-compliant version of Guillaume’s solution:

#import <Foundation/Foundation.h>

@interface LaunchServicesWrapper : NSObject

+ (BOOL)setMyselfAsDefaultApplicationForFileExtension:
  (NSString *)fileExtension;

@end


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

@implementation LaunchServicesWrapper

+ (NSString *)UTIforFileExtension:(NSString *)extension
{
  return (NSString *)CFBridgingRelease(
    UTTypeCreatePreferredIdentifierForTag(
      kUTTagClassFilenameExtension, (__bridge CFStringRef)extension,
      NULL
    )
  );
}

+ (BOOL)setMyselfAsDefaultApplicationForFileExtension:
  (NSString *)fileExtension
{
  return LSSetDefaultRoleHandlerForContentType(
    (__bridge CFStringRef) [LaunchServicesWrapper
    UTIforFileExtension:fileExtension], kLSRolesAll,
    (__bridge CFStringRef) [[NSBundle mainBundle]
    bundleIdentifier]
  );
}

@end
like image 43
Rafael Bugajewski Avatar answered Nov 16 '22 23:11

Rafael Bugajewski