loginitem
+ (BOOL) willStartAtLogin:(NSURL *)itemURL { Boolean foundIt=false; LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); if (loginItems) { UInt32 seed = 0U; NSArray *currentLoginItems = [NSMakeCollectable(LSSharedFileListCopySnapshot(loginItems, &seed)) autorelease]; for (id itemObject in currentLoginItems) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)itemObject; UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef URL = NULL; OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); if (err == noErr) { foundIt = CFEqual(URL, itemURL); CFRelease(URL); if (foundIt) break; } } CFRelease(loginItems); } return (BOOL)foundIt; } + (void) setStartAtLogin:(NSURL *)itemURL enabled:(BOOL)enabled { OSStatus status; LSSharedFileListItemRef existingItem = NULL; LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); if (loginItems) { UInt32 seed = 0U; NSArray *currentLoginItems = [NSMakeCollectable(LSSharedFileListCopySnapshot(loginItems, &seed)) autorelease]; for (id itemObject in currentLoginItems) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)itemObject; UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef URL = NULL; OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); if (err == noErr) { Boolean foundIt = CFEqual(URL, itemURL); CFRelease(URL); if (foundIt) { existingItem = item; break; } } } if (enabled && (existingItem == NULL)) { LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, (CFURLRef)itemURL, NULL, NULL); } else if (!enabled && (existingItem != NULL)) LSSharedFileListItemRemove(loginItems, existingItem); CFRelease(loginItems); } }
If you want an easy to implement checkbox, make a @property BOOL startAtLogin;
in one of your classes and implement it as follows. Just bind the checkbox value to the property and it should all work seamlessly.
- (NSURL *)appURL { return [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; } - (BOOL)startAtLogin { return [LoginItem willStartAtLogin:[self appURL]]; } - (void)setStartAtLogin:(BOOL)enabled { [self willChangeValueForKey:@"startAtLogin"]; [LoginItem setStartAtLogin:[self appURL] enabled:enabled]; [self didChangeValueForKey:@"startAtLogin"]; }