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

。_饼干妹妹 提交于 2019-12-08 08:50:51

问题


If I can explain my self better knowing if a user is running some particular program such as word or chrome, etc.

I will try to update my question as I write code or find more information.

Thank you (:


回答1:


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
}


来源:https://stackoverflow.com/questions/37646605/how-can-you-get-information-such-as-users-window-for-example-using-the-nstask-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!