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
chrome
XCode
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);
}
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.