Search code examples
objective-cmacoscocoaitunesobserver-pattern

Add observer for a process in Cocoa


I'm developing kind of a plugin for iTunes.

A lot of user have requested, that they would like to start the plugin if they start iTunes, which of course makes sense. However, I'm not sure how to do this.

I thought about a helper app, which is probably the only way. The only thing that bothers me is how to get the notification. Of course I could consistently check if iTunes is running, but I'm not sure if that's the right way to do it.

I would rather add my app as an observer of that process. Is that possible?

If not, how does Activity Monitor do it?


SOLUTION

Thanks to Daij-Djan! I got it working like this:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
                                                           selector:@selector(iTunesLaunched:)
                                                               name:NSWorkspaceDidLaunchApplicationNotification
                                                             object:nil];

    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
                                                           selector:@selector(iTunesTerminated:)
                                                               name:NSWorkspaceDidTerminateApplicationNotification
                                                             object:nil];
}

-(void) iTunesLaunched:(NSNotification *)notification {
    NSRunningApplication *runApp = [[notification userInfo] valueForKey:@"NSWorkspaceApplicationKey"];
    if ([runApp.bundleIdentifier isEqualToString:@"com.apple.iTunes"])
        NSLog(@"start");

}

-(void) iTunesTerminated:(NSNotification *)notification {
    NSRunningApplication *runApp = [[notification userInfo] valueForKey:@"NSWorkspaceApplicationKey"];
    if ([runApp.bundleIdentifier isEqualToString:@"com.apple.iTunes"])
        NSLog(@"terminate");

}

Solution

  • register for NSWorkspace notifications:
    NSWorkspaceDidLaunchApplicationNotification
    NSWorkspaceDidTerminateApplicationNotification

    see https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html


    there is also the possibility to KVO the runningApplications property
    btw cocoatech has a nice NTRunningAppManager class that does just that