且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为Mac App创建助手应用程序以在用户登录时启动它?

更新时间:2023-01-26 11:54:59

+ (void)startHelper {
    NSURL *helperURL = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:@"Contents/Library/LoginItems/YourHelper.app" isDirectory:YES];
    OSStatus status = LSRegisterURL((CFURLRef)helperURL, YES);
    if (status != noErr) {
        NSLog(@"Failed to LSRegisterURL '%@': %jd", helperURL, (intmax_t)status);
    }


    Boolean success = SMLoginItemSetEnabled(CFSTR("com.yourcompany.helper-CFBundleIdentifier-here"), YES);
    if (!success) {
        NSLog(@"Failed to start Helper");
    }
}

请注意,Helper必须与主应用程序打包在"Contents/Library/LoginItems"目录中.您将需要在构建过程中创建它,并在其中复制帮助程序.

Note that the Helper must be packaged with the main app in the "Contents/Library/LoginItems" directory. You will need to create it during the build and copy the helper there.