How can you get information such as, users window for example using the NSTask class in Swift, for OSX apps?

穿精又带淫゛_ 提交于 2019-12-06 19:42:30

You don't have to go through NSTask, you can use Cocoa's NSWorkspace to get the list of running applications:

import Cocoa
let apps = NSWorkspace.sharedWorkspace().runningApplications

It returns an array of NSRunningApplication objects.

Let's say you want the running applications names in an array:

let appsNames = apps.flatMap { $0.localizedName }

If you want to know for example if iTunes is running:

if appsNames.contains("iTunes") {
    // iTunes is running
}

Note, a more precise way to find a running app would be to use the bundle identifier:

let bundleNames = apps.flatMap { $0.bundleIdentifier }
if bundleNames.contains("com.apple.iTunes") {
    // iTunes is running
}

If you want to know which app is active (has its window frontmost):

let actives = apps.filter { $0.active }
if let active = actives.first {
    // "active" is the frontmost app
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!