Search code examples
swiftmacoscocoafor-loopnsrunningapplication

How to add listener for all running applications


I want to display a list of all running application names.

Issue: It doesn't add an app that is running after the function is called. Therefore, it doesn't add the app name to the list simultaneously.

Goal: I want to add a listener, so if a new app is running it will add it to the array simultaneously without restarting the app or recalling the function again.

func allRunningApplications() {

        for runningApplication in NSWorkspace.shared.runningApplications {

            let appName = runningApplication.localizedName

            // Add App Name to Array
            array.append(appName)
    }
}

Solution

  • I mentioned the "did launch", et. al., notifications because you didn't explain why you wanted to monitor the set of running applications.

    If you are only interested in whether a specific app has launched (or quit), it would probably be easier to use the NSWorkspace notifications:

    (untested code)

    let center = NSWorkspace.shared.notificationCenter
    center.addObserver(forName: NSWorkspace.didLaunchApplicationNotification,
                        object: nil, // always NSWorkspace
                         queue: OperationQueue.main) { (notification: Notification) in
                            if let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication {
                                if app.bundleIdentifier == "com.apple.Terminal" {
                                    // User just launched the Terminal app; should we be worried?
                                }
                            }
    }
    

    Note that workspace notifications are posted to NSWorkspace's private notification center, not the default notification center, so remember to add your observers there.