Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Darkroom

Guest
Original poster
Dec 15, 2006
2,445
0
Montréal, Canada
i know it's possible to launch an app with NSWorkspace, but i'd like to know how i can look for an app that is currently active. Something like:

Code:
NSWorkspace * ws = [NSWorkspace sharedWorkspace];

if ([ws launchedApplications.Safari])
{
NSLog (@"Safari Is Running");
}
else
{
NSLog (@"Safari Is Not Running");
}

???
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
launchedApplications returns an array of dictionaries, so you'll have to loop through it and check each dictionary, comparing the @"NSApplicationName" key.

If you need to get info on the frontmost app, you can use the activeApplication method which will return the same kind of dictionary.
 

Darkroom

Guest
Original poster
Dec 15, 2006
2,445
0
Montréal, Canada
something like this?:

Code:
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
NSArray * openApps;
openApps = [ws valueForKeyPath:@"launchedApplications.NSApplicationName"];
if ([openApps == @"launchedApplications.Safari"])
	NSLog (@"Safari Is Running");
	}
	else
	{
	NSLog (@"Safari Is Not Running");
	}

not getting it

sorry if the code here is dumb, i have a cold and my brain isn't functioning as average as it usually is :p
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
I wouldn't use Key Value Coding (valueForKeyPath:) if you don't know what it's doing. It's nice if you do, because it reduces code, but if not it can be confusing.

I'd suggest brushing up on arrays and dictionaries if you're not sure where to go from here. Also your syntax isn't correct. I get what you're trying to do, but it doesn't work that way ;)
 

Darkroom

Guest
Original poster
Dec 15, 2006
2,445
0
Montréal, Canada
alright... i got it...

Code:
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSArray *runningAppDictionaries = [ws launchedApplications];
NSDictionary *aDictionary;
        
for (aDictionary in runningAppDictionaries)
	{
[COLOR="SeaGreen"]//	NSLog(@"Open App: %@", [aDictionary valueForKey:@"NSApplicationName"]);[/COLOR]

	if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"Safari"])
		{
		NSLog(@"Safari Is Running");
		break;
		}
	}

seems to work fine. anything that should be changed? is it really OK to try and match the application name? or should it be with the bundle identifier com.apple.safari? i guess it would matter for localization, like Address Book (which has a localized name)... ??

[EDIT] it's probably best to use the bundle identifier rather than the app's name

Code:
if ([[aDictionary valueForKey:@"NSApplicationBundleIdentifier"] isEqualToString:@"com.apple.safari"])
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.