Class

NSWorkspace

An NSWorkspace object can launch other apps and perform a variety of file-handling services.

Overview

There is one shared NSWorkspace object per app. You use the class method shared() to access it. For example, the following statement uses an NSWorkspace object to request that a file be opened in the TextEdit app:

[[NSWorkspace sharedWorkspace] openFile:@"/Myfiles/README"
    withApplication:@"TextEdit"];

You can use the workspace object to:

  • Open, manipulate, and get information about files and devices

  • Track changes to the file system, devices, and the user database

  • Get and set Finder information for files

  • Launch apps

Legacy Constants

Table 1 describes keys for an NSDictionary object containing information about an app. This dictionary is returned by activeApplication() and launchedApplications, and is also provided in the userInfo of NSWorkspace notifications for app launch and termination.

Note that these constants are considered legacy.

Table 1

userInfo dictionary keys for activeApplication and launchedApplications and notifications for app launch and termination

Key

Value

@"NSApplicationPath"

The full path to the app, as a NSString object.

@"NSApplicationName"

The app's name, as an NSString object.

@"NSApplicationBundleIdentifier"

The app’s bundle identifier, as an NSString object.

@"NSApplicationProcessIdentifier"

The app's process id, as an NSNumber object.

@"NSApplicationProcessSerialNumberHigh"

The high long of the process serial number (PSN), as an NSNumber object.

@"NSApplicationProcessSerialNumberLow"

The low long of the process serial number (PSN), as an NSNumber object.

Symbols

Accessing the Shared NSWorkspace Instance

class func shared()

Returns the shared NSWorkspace instance.

Accessing the NSWorkspace Notification Center

var notificationCenter: NotificationCenter

Returns the notification center for workspace notifications.

Opening Files

func open(URL)

Opens the location at the specified URL.

func openFile(String)

Opens the specified file specified using the default app associated with its type.

func openFile(String, withApplication: String?)

Opens a file using the specified app.

func openFile(String, withApplication: String?, andDeactivate: Bool)

Opens the specified file and optionally deactivates the sending app.

func openFile(String, from: NSImage?, at: NSPoint, in: NSView?)

Opens a file using the default app for its type and animates the action using a custom icon.

Deprecated

Manipulating Applications

func launchApplication(String)

Launches the specified app.

func launchApplication(String, showIcon: Bool, autolaunch: Bool)

Launches the specified app using additional options.

func hideOtherApplications()

Hides all applications other than the sender.

Manipulating Files

func duplicate([URL], completionHandler: (([URL : URL], Error?) -> Void)? = nil)

Duplicates the specified URLS asynchronously in the same manner as the Finder.

func recycle([URL], completionHandler: (([URL : URL], Error?) -> Void)? = nil)

Moves the specified URLs to the trash in the same manner as the Finder.

func performFileOperation(String, source: String, destination: String, files: [Any], tag: UnsafeMutablePointer<Int>?)

Performs a file operation on a set of files in a particular directory.

Deprecated
func activateFileViewerSelecting([URL])

Activates the Finder, and opens one or more windows selecting the specified files.

func selectFile(String?, inFileViewerRootedAtPath: String)

Selects the file specified by fullPath.

Manipulating Uniform Type Identifier Information

func type(ofFile: String)

Returns the uniform type identifier of the specified file, if it can be determined..

func localizedDescription(forType: String)

Returns the localized description for the specified Uniform Type Identifier

func preferredFilenameExtension(forType: String)

Returns the preferred filename extension for the specified Uniform Type Identifier.

func filenameExtension(String, isValidForType: String)

Returns whether the specified filename extension is appropriate for the Uniform Type Identifier.

func type(String, conformsToType: String)

Returns a Boolean indicating that the first Uniform Type Identifier conforms to the second Uniform Type Identifier.

func urlForApplication(withBundleIdentifier: String)

Returns the URL for the app with the specified identifier.

Requesting Information

func urlForApplication(toOpen: URL)

Returns the URL to the default app that would be used to open the given URL.

func fullPath(forApplication: String)

Returns the full path for the specified app.

func isFilePackage(atPath: String)

Determines whether the specified path is a file package.

var frontmostApplication: NSRunningApplication?

Returns the frontmost app, which is the app that receives key events.

var runningApplications: [NSRunningApplication]

Returns an array of NSRunningApplication representing the running apps.

var menuBarOwningApplication: NSRunningApplication?

Returns the app that owns the currently displayed menu bar.

Managing Icons

func icon(forFile: String)

Returns an image containing the icon for the specified file.

func icon(forFileType: String)

Returns an image containing the icon for files of the specified type.

func icon(forFiles: [String])

Returns an image containing the icon for the specified files.

func setIcon(NSImage?, forFile: String, options: NSWorkspaceIconCreationOptions = [])

Sets the icon for the file or directory at the specified path.

Unmounting a Device

func unmountAndEjectDevice(atPath: String)

Unmounts and ejects the device at the specified path.

func unmountAndEjectDevice(at: URL)

Attempts to eject the volume mounted at the given path.

Managing the Desktop Image

func desktopImageURL(for: NSScreen)

Returns the URL for the desktop image for the given screen.

func setDesktopImageURL(URL, for: NSScreen, options: [String : Any] = [:])

Sets the desktop image for the given screen to the image at the specified URL.

func desktopImageOptions(for: NSScreen)

Returns the desktop image options for the given screen.

Performing Finder Spotlight Searches

func showSearchResults(forQueryString: String)

Displays a Spotlight search results window in Finder for the specified query string.

Finder File Labels

var fileLabelColors: [NSColor]

Returns the corresponding array of file label colors for the file labels.

var fileLabels: [String]

Returns the array of file labels as strings.

Tracking Changes to the File System

func noteFileSystemChanged(String)

Informs the workspace object that the file system changed at the specified path.

Requesting Additional Time Before Logout

func extendPowerOff(by: Int)

Requests the system wait for the specified amount of time before turning off the power or logging out the user.

Supporting Accessibility

var accessibilityDisplayShouldDifferentiateWithoutColor: Bool

A Boolean value that indicates whether the app should avoid conveying information through color alone.

var accessibilityDisplayShouldIncreaseContrast: Bool

A Boolean value that indicates whether the app should present a high contrast user interface.

var accessibilityDisplayShouldReduceTransparency: Bool

A Boolean value that indicates whether the app should avoid using semitransparent backgrounds.

Deprecated Methods

func mountedRemovableMedia()

Returns the full pathnames of all currently mounted removable disks.

Deprecated
func mountedLocalVolumePaths()

Returns the mount points of all local volumes, not just the removable ones returned by mountedRemovableMedia().

Deprecated
func activeApplication()

Returns a dictionary with information about the current active app.

Deprecated

Constants

Workspace Launch Configuration Options

The following keys can be used in the configuration dictionary of the launchApplication(at:options:configuration:) method. Each key is optional, and if omitted, default behavior is applied.

File Operations

These constants specify different types of file operations used by performFileOperation(_:source:destination:files:tag:).

Desktop Image Dictionary Keys

The following keys may be specified or returned in the options dictionary for setDesktopImageURL(_:for:options:).

Volume Mounting Notification User Info Keys

The following keys are available in the userInfo parameter of the notification named NSWorkspaceDidRenameVolume.

NSWorkspaceDidRenameVolumeNotification User Info Keys

The following keys are available in the userInfo parameter of the notification named NSWorkspaceDidRenameVolume.

NSWorkspaceApplicationKey User Info Key

This constant is supplied in the userInfo dictionary of various notifications.

NSWorkspaceIconCreationOptions

These constants describe the NSWorkspaceIconCreationOptions values used by setIcon(_:forFile:options:). You can combine these using the C bitwise OR operator.

Notifications

All NSWorkspace notifications are posted to the NSWorkspace object’s own notification center, not the app’s default notification center. Access this center using the NSWorkspace object’s notificationCenter method.

static let NSWorkspaceWillLaunchApplication: NSNotification.Name

Posted when the Finder is about to launch an app.

static let NSWorkspaceSessionDidResignActive: NSNotification.Name

Posted before a user session is switched out.

static let NSWorkspaceDidActivateApplication: NSNotification.Name

Posted when the Finder is about to activate an app.

static let NSWorkspaceDidRenameVolume: NSNotification.Name

Posted when a volume changes its name and/or mount path. These typically change simultaneously, in which case only one notification is posted.

static let NSWorkspaceDidMount: NSNotification.Name

Posted when a new device has been mounted.

static let NSWorkspaceWillUnmount: NSNotification.Name

Posted when the Finder is about to unmount a device.

static let NSWorkspaceDidUnmount: NSNotification.Name

Posted when the Finder did unmount a device.

static let NSWorkspaceDidPerformFileOperation: NSNotification.Name

Posted when a file operation has been performed in the receiving app.

Deprecated
static let NSWorkspaceDidChangeFileLabels: NSNotification.Name

Posted when the Finder file labels or colors change.

static let NSWorkspaceDidWake: NSNotification.Name

Posted when the machine wakes from sleep.

static let NSWorkspaceWillPowerOff: NSNotification.Name

Posted when the user has requested a logout or that the machine be powered off.

static let NSWorkspaceWillSleep: NSNotification.Name

Posted before the machine goes to sleep.

static let NSWorkspaceScreensDidSleep: NSNotification.Name

Posted when the machine’s screen goes to sleep.

static let NSWorkspaceScreensDidWake: NSNotification.Name

Posted when the machine’s screens wake.

static let NSWorkspaceAccessibilityDisplayOptionsDidChange: NSNotification.Name

Posted when any of the accessibility display options change.

Relationships

Inherits From

Conforms To