Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Cocoa application add itself as a global login item?

Tags:

macos

cocoa

login

I tried

LSSharedFileListRef globalLoginItems = LSSharedFileListCreate(NULL, kLSSharedFileListGlobalLoginItems, NULL);
if (globalLoginItems) {
    LSSharedFileListItemRef ourLoginItem = LSSharedFileListInsertItemURL(globalLoginItems,
                                                                         kLSSharedFileListItemLast,
                                                                         NULL, NULL,
                                                                         (CFURLRef)[[NSBundle mainBundle] bundleURL], 
                                                                         NULL, NULL);
    if (ourLoginItem) {
        CFRelease(ourLoginItem);
    } else {
        NSLog(@"Could not insert ourselves as a global login item");
    }

    CFRelease(globalLoginItems);
} else {
    NSLog(@"Could not get the global login items");
}

LSSharedFileListInsertItemURL() just returned NULL when I built and ran the application. Is there something else that I need to do? Some kind of authorization?

NOTE: The use-case here is for global login items, that is using kLSSharedFileListGlobalLoginItems and not kLSSharedFileListSessionLoginItems.

like image 806
Plumenator Avatar asked Mar 27 '11 12:03

Plumenator


1 Answers

I got this working. All I had to do was add these lines before I insert the app into the login items:

AuthorizationRef auth = NULL; 
AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
LSSharedFileListSetAuthorization(globalLoginItems, auth);

The docs for LSSharedFileListSetAuthorization say that we have to get the right system.global-login-items for this, but it worked nevertheless!

But this will fail if the user is not an administrator. For it to work then too, you'll have to do this:

AuthorizationItem right[1] = {{"system.global-login-items.", 0, NULL, 0}};
AuthorizationRights setOfRights = {1, right};
AuthorizationRef auth = NULL; 
AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);


AuthorizationCopyRights(auth, &setOfRights, kAuthorizationEmptyEnvironment,
                              (kAuthorizationFlagDefaults
                               | kAuthorizationFlagInteractionAllowed
                               | kAuthorizationFlagExtendRights), NULL);

It's also advisable to refer to the docs for details.

like image 98
Plumenator Avatar answered Nov 15 '22 05:11

Plumenator