Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuxiaowei/51068dcd073ab203f7b2d4ced69f1544 to your computer and use it in GitHub Desktop.
Save wuxiaowei/51068dcd073ab203f7b2d4ced69f1544 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment