Ramaprasad Upadhyaya
Ramaprasad Upadhyaya

Reputation: 467

Single Instance Application- Activate Window - Cocoa

I have two cocoa apps. Application1 calls Application2(abc.app) as below-

if ([[NSWorkspace sharedWorkspace] respondsToSelector:@selector(launchApplicationAtURL:options:configuration:error:)])
    return nil != [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:@"abc.app" isDirectory:NO] options:NSWorkspaceLaunchDefault  configuration:nil error:NULL];

This should open Application2 (abc.app). Now If application 1 calls application 2 again, I want to activate abc.app (If this is minimised in the dock).I want to ensure there is single instance of abc.app running. How can we achieve this?

Upvotes: 1

Views: 1258

Answers (3)

Emmanuel
Emmanuel

Reputation: 2917

You can check if your second application is running and check if it's the active application (frontmost) with NSRunningApplicationclass.

// check if abc.app is running
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.youApplication.abc"];
if ([apps count] == 0)
{
    // not running, launch it
    [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:@"abc.app" isDirectory:NO] options:NSWorkspaceLaunchDefault  configuration:nil error:NULL];
}



// check if abc.app is frontmost
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.youApplication.abc"];
if ([apps count])
{
    // abc.app is running, check if active
    if (![(NSRunningApplication*)[apps objectAtIndex:0] isActive])
    {
        // not active, activate it
        [(NSRunningApplication*)[apps objectAtIndex:0] activateWithOptions: NSApplicationActivateAllWindows];
    }
}

Upvotes: 2

uliwitness
uliwitness

Reputation: 8783

Not quite sure of your problem. Mac OS X by default only launches one instance of an app. (Unless you have several physical copies of the executable on disk, but even for that case there's an Info.plist key that prohibits launching an app if one with the same bundle ID is already running).

Also, by default, NSWorkspace should bring to front and un-collapse your application if it has no other windows open (it should behave as if you'd double-clicked it again in Finder, or clicked its dock icon when it's already running), and it will call the second app's 'reopen application' handler.

If it doesn't do it, you could try to explicitly un-collapse your main window from the 'reopen' delegate method, or if you don't want this to happen generally (but why wouldn't you?), you could look into sending an Apple Event between the two applications.

Also, you can check if the second application is already running by looking at the runningApplications and looking for an entry with the same bundle ID.

Upvotes: 3

Fran Martin
Fran Martin

Reputation: 2369

You can´t from App1. You can check if your App2 is launched from App2 with Notifications like here

Upvotes: 0

Related Questions