Skip to content

Instantly share code, notes, and snippets.

@joerick
Created September 15, 2014 11:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save joerick/73670eba228c177bceb3 to your computer and use it in GitHub Desktop.
Save joerick/73670eba228c177bceb3 to your computer and use it in GitHub Desktop.
Launch at login category on NSApplication
//
// NSApplication+MXUtilities.h
// Mixim
//
// Created by Joe Rickerby on 15/09/2014.
// Copyright (c) 2014 Mixim Technology Ltd. Released under BSD Licence.
//
#import <Cocoa/Cocoa.h>
@interface NSApplication (MXUtilities)
@property (nonatomic, assign) BOOL launchAtLogin;
@end
//
// NSApplication+MXUtilities.m
// Mixim
//
// Created by Joe Rickerby on 15/09/2014.
// Copyright (c) 2014 Mixim Technology Ltd. Released under BSD Licence.
//
#import "NSApplication+MXUtilities.h"
@implementation NSApplication (MXUtilities)
- (BOOL)launchAtLogin
{
LSSharedFileListItemRef loginItem = [self loginItem];
BOOL result = loginItem ? YES : NO;
if (loginItem) {
CFRelease(loginItem);
}
return result;
}
- (void)setLaunchAtLogin:(BOOL)launchAtLogin
{
if (launchAtLogin == self.launchAtLogin) {
return;
}
LSSharedFileListRef loginItemsRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (launchAtLogin) {
CFURLRef appUrl = (__bridge CFURLRef)[[NSBundle mainBundle] bundleURL];
LSSharedFileListItemRef itemRef = LSSharedFileListInsertItemURL(loginItemsRef, kLSSharedFileListItemLast, NULL,
NULL, appUrl, NULL, NULL);
if (itemRef) CFRelease(itemRef);
} else {
LSSharedFileListItemRef loginItem = [self loginItem];
LSSharedFileListItemRemove(loginItemsRef, loginItem);
if (loginItem != nil) CFRelease(loginItem);
}
if (loginItemsRef) CFRelease(loginItemsRef);
}
#pragma mark Private
- (LSSharedFileListItemRef)loginItem
{
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
LSSharedFileListRef loginItemsRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (!loginItemsRef) {
return NULL;
}
NSArray *loginItems = CFBridgingRelease(LSSharedFileListCopySnapshot(loginItemsRef, nil));
LSSharedFileListItemRef result = NULL;
for (id item in loginItems) {
LSSharedFileListItemRef itemRef = (__bridge LSSharedFileListItemRef)item;
CFURLRef itemURLRef;
if (LSSharedFileListItemResolve(itemRef, 0, &itemURLRef, NULL) == noErr) {
NSURL *itemURL = (__bridge NSURL *)itemURLRef;
if ([itemURL isEqual:bundleURL]) {
result = itemRef;
break;
}
}
}
if (result != nil) {
CFRetain(result);
}
CFRelease(loginItemsRef);
return result;
}
@end
@mhermosi
Copy link

Do you have an example with swift 3/4, also LSSharedFileListCreate seems to be deprecated as well as it's related constants... given that... what would be the best approach to accomplish this task?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment