Home > front end >  SMAppService register() - How to detect launch at startup/login vs regular launch?
SMAppService register() - How to detect launch at startup/login vs regular launch?

Time:12-09

We use the new MacOS Ventura SMAppService functionality to offer a "Launch at Login" feature to our users. We do this in a very straightforward way:

SMAppService.mainApp.register()

We'd like to do some specific processing if we are launched at startup/login that we wouldn't do if just launched regularly. Specifically our users would prefer not to see any windows/UI if launched at startup as a menu bar app.

Is there any way to detect that our App has been launched at startup/login vs a regular user initiated launch?

Perhaps a command line argument or is there a special parent process we could look for? There doesn't seem to be a way to pass command line arguments and we don't know of any special parent process we could look for.

CodePudding user response:

To answer my own question, it turns out this is possible. Inspired by this older answer which worked with the non Ventura API/paradigm.

Inside your AppDelegate:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSAppleEventDescriptor* event = NSAppleEventManager.sharedAppleEventManager.currentAppleEvent;
    
    BOOL launchedAsLoginItem = (event.eventID == kAEOpenApplication &&
       [event paramDescriptorForKeyword:keyAEPropData].enumCodeValue == keyAELaunchedAsLogInItem);

    ...
}

and Swift:

let event = NSAppleEventManager.shared().currentAppleEvent
let launchedAsLogInItem =
    event?.eventID == kAEOpenApplication &&
    event?.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem
  • Related