Search code examples
objective-cmacoscocoansworkspacensrunningapplication

Filter [NSWorkspace runningApplications] to contain only user applications (no daemons/UIAgents)


Is there a way to filter the list of applications given by [NSWorkspace runningApplications] to hide all daemons, etc short of manually checking each application's plist for the UIAgent key? If an application doesn't show in the dock, I'm not interested in it.


Solution

  • UPDATE: If you’re using Objective-C, my original answer below still applies, but if you’re using Swift this can very easily be performed more cleanly, thanks to Swift’s filter function for collection types.

    let workspace = NSWorkspace.sharedWorkspace()
    let apps = workspace.runningApplications.filter { (app) -> Bool in
        return app.activationPolicy == .Regular
    };
    

    In Objective-C something similar can be done with NSArray’s various predicate-based and enumeration methods, but they’ll be a little more long-winded than their Swift counterpart.


    I found the answer after some searching, but it's something that might not be immediately obvious.

    An easy way to only grab processes which have icons in the Dock is by doing a simple fast enumeration loop and checking each NSRunningApplication's activationPolicy, like so:

    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSArray *apps = [workspace runningApplications];
    
    for (NSRunningApplication *a in apps) {
        if (a.activationPolicy == NSApplicationActivationPolicyRegular) {
            // Do stuff here
        }
    }
    

    Typically, applications with normal windows and dock icons use NSApplicationActivationPolicyRegular. Menu extras and Alfred-type applications use NSApplicationActivationPolicyAccessory. Daemons, etc with no user visibility whatsoever use NSApplicationActivationPolicyProhibited. These constants correspond with the LSUIElement and LSBackgroundOnly keys in each application's Info.plist.

    This approach should catch applications which have settings that allow the user to toggle the presence of the application's dock icon through setting their activationPolicy dynamically.