Cocoa应用程序如何将自身添加为全局登录项?

Plu*_*tor 5 macos cocoa login

我试过了

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");
}
Run Code Online (Sandbox Code Playgroud)

当我构建并运行应用程序时,LSSharedFileListInsertItemURL()刚刚返回NULL.我还需要做些什么吗?某种授权?

注意:此处的用例是针对全局登录项,即使用kLSSharedFileListGlobalLoginItems而不是kLSSharedFileListSessionLoginItems.

Plu*_*tor 5

我得到了这个工作.在将应用程序插入登录项之前,我所要做的就是添加这些行:

AuthorizationRef auth = NULL; 
AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
LSSharedFileListSetAuthorization(globalLoginItems, auth);
Run Code Online (Sandbox Code Playgroud)

文档LSSharedFileListSetAuthorization说我们必须得到这个权利system.global-login-items,但它仍然有效!

但如果用户不是管理员,这将失败.为了它也可以工作,你必须这样做:

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);
Run Code Online (Sandbox Code Playgroud)

建议您参考文档以获取详细信息.