4

I want to be notified when an application is started on Mac OSX. I found Cocoa Application Finished Launch and that seemed to answer my question, but the callback method appDidLaunch is not being called when Preview get's launched.

Here's what I have so far,

#import <Foundation/Foundation.h>
#import <Appkit/Appkit.h>

@interface test_case: NSObject
-(void)run;
@end

@implementation test_case: NSObject

- (void)appDidLaunch:(NSNotification*)note
{
    NSLog(@"app launched: %@", [note userInfo]);
}

-(void)run {
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(appDidLaunch:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];

    [[NSWorkspace sharedWorkspace] openFile:@"/Users/nah/Desktop/bsd_hacks.pdf"
        withApplication:@"Preview"];
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        test_case * t = [[test_case alloc] init];

        [t run];
    }
    return 0;
}

So why is appDidLaunch not being called?

Community
  • 1
  • 1
2trill2spill
  • 1,333
  • 2
  • 20
  • 41

1 Answers1

3

Your application ends execution (exit main function) before you have a chance to receive notification. Moreover, you need to correctly setup main run loop to handle notification. Usually, NSApplicationMain call does all the application setup for you. So, the easiest way to fix an issue, is next change in main function:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        test_case * t = [[test_case alloc] init];
        [t run];
        return NSApplicationMain(argc, argv);
    }
}
Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
  • Is there a way to detect a launch of a **background application**, e.g. a menu bar application like Viscosity etc.? Apple says that "the system does not post [NSWorkspaceWillLaunchApplicationNotification] for background apps or for apps that have the `LSUIElement` key in their `Info.plist` file. If you want to know when all apps (including background apps) are launched or terminated, use key-value observing to monitor the value returned by the `runningApplications` method." I would like to add that to my listener posted here: https://stackoverflow.com/q/52710089/6699322 – JayB Oct 11 '18 at 13:32