我正在使用该ServiceManagement
框架添加一个登录项,该登录项将启动一个帮助应用程序,该应用程序将在用户重新登录时启动主应用程序。如果用户选择或取消选择“登录时启动” ,则调用addLoginItem
and方法开关类型:disableLoginItem
NSButton
//Add the Helper app as a login item
- (void)addLoginItem
{
NSLog(@"Enable login item");
if (!SMLoginItemSetEnabled((__bridge CFStringRef)kLoginHelperBundleIdentifier, true)) {
}
}
//Disable the Helper app as a login item
- (void)disableLoginItem
{
NSLog(@"Disable login item");
if (!SMLoginItemSetEnabled((__bridge CFStringRef)kLoginHelperBundleIdentifier, false)) {
}
}
助手应用程序的代码相当简单......
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
[[NSWorkspace sharedWorkspace] launchApplication: @"My App"];
[[NSApplication sharedApplication] terminate:self];
}
问题在于,当主应用程序运行时,如果用户反复选择并偏转“登录时启动”按钮,则会启动主应用程序的第二个实例。然而,我想要发生的是主应用程序只会在用户重新登录时启动。
在查看 时SMLoginItem.h
,我看到文档说明了以下内容:
* @param enabled
* The Boolean enabled state of the helper application. This value is effective
* only for the currently logged in user. If true, the helper application will
* be started immediately (and upon subsequent logins) and kept running. If
* false, the helper application will no longer be kept running.
因此,似乎每次addLoginItem
调用 Helper App 时都会启动。知道了这一点,我修改了我的 Helper App 以检查我的主应用程序是否已经在运行。如果是,那么我们将终止 Helper App。否则,我们将启动 Main App 的一个实例,然后终止 Helper App。
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
if ([NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.myCompany.MyApp"]){
[[NSApplication sharedApplication] terminate:self];
}
else {
[[NSWorkspace sharedWorkspace] launchApplication: @"My App"];
[[NSApplication sharedApplication] terminate:self];
}
}
但是,如果用户反复选择和取消选择“登录时启动”按钮,则会创建主应用程序的第二个实例。如果用户多次切换“登录时启动”,是否有人知道如何确保辅助应用程序没有创建主应用程序的第二个实例?
编辑该应用程序没有通过 Mac App Store 分发,这就是为什么我没有按照本教程中的说明启用代码签名或沙盒。