swiftmacosnsworkspace

Use NSRunningApplications?


I am trying to have my OS X Application detect if a certain program is running but NSRunningApplications isn't working for me. This is my code:

import AppKit
class func sharedWorkspace() -> NSWorkspace
{
    var runningApplications: [NSRunningApplications] {get}
}

The error I'm getting is

Expected '{' to start getter definition.

as well as

Missing return in a function expected to return 'NSWorkspace.

Any ideas?


Solution

  • You've got to use NSWorkspace.sharedWorkspace().runningApplications itself:

    for app in NSWorkspace.sharedWorkspace().runningApplications {
        if let name = app.localizedName {
            print(name)
        }
    }
    

    You can get the running applications names in an array with a simple map (or flatMap here to manage Optionals):

    let names = NSWorkspace.sharedWorkspace().runningApplications.flatMap { $0.localizedName }
    
    print(names)