Marco Pashkov Marco Pashkov - 3 years ago 120
Swift Question

How to retrieve the OSX application that currently receives key events

I am following the cocoa documentation to determine the current front most application in OSX - aka the application which receives key events.
However, when I am executing the following swift the API always returns me the same value -

XCode
, but it never changes to
chrome
or any other application when I switch to them. I also tried to execute the compiled program but instead of constantly showing
XCode
it now shows whichever terminal app I am running.

What is the correct way of determining the application that receives the key events from OSX? Is my code in this regard broken?

import Cocoa

func getActiveApplication() -> String{
// Return the localized name of the currently active application
let ws = NSWorkspace.sharedWorkspace()
let frontApp = ws.frontmostApplication
return frontApp.localizedName
}

var frontMostApp : String
while true {
frontMostApp = getActiveApplication();
NSLog("front app: %@", frontMostApp)
sleep(1);
}

Answer Source

You you should do one thing differently, that is follow the NSWorkSpace notifications that tell you the applications resigned active or became active. This is key especially as you are running in debug mode. In debug mode Xcode is spawning your app as a child process. In release mode it is basically doing the same as calling the open command in terminal. In debug mode if you call this code too early and only once, you're not catching changes. Remember it's dynamic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download