Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX/Swift Get Frontmost Running Application

Tags:

macos

swift

I'm new to swift and osx programming in general, and I need help with one thing that I can't seem to find an answer for. I'm trying to get the frontmost application running on a computer through an app. Right now I'm able to detect when a target application opens, but not when it is in front of all other windows or when it goes into the background. What I have so far is:

var workspace = NSWorkspace.sharedWorkspace()
var applications = workspace.runningApplications
for app in applications {
    let x = "LolClient"
    if app.localizedName == x {
        println("League is open")
    }
}

That will just tell me when a target app opens. I just need to identify what app is in front of all others... basically which one is recieving keystrokes etc. What code would I need to do this? Thank you in advance.

like image 332
Anshul Singh Avatar asked Jul 11 '16 18:07

Anshul Singh


2 Answers

I think you want NSWorkspace.shared.frontmostApplication.

like image 54
rob mayoff Avatar answered Oct 05 '22 03:10

rob mayoff


NSWorkspace.shared.frontmostApplication

For the name of the app:

NSWorkspace.shared.frontmostApplication?.localizedName
like image 40
Steve Butabi Avatar answered Oct 05 '22 05:10

Steve Butabi