Swift 4 Version:
Declare NSWorkspace in applicationDidFinishLaunching and add observers for mount and unmount events.
let workspace = NSWorkspace.shared workspace.notificationCenter.addObserver(self, selector: #selector(didMount(_:)), name: NSWorkspace.didMountNotification, object: nil) workspace.notificationCenter.addObserver(self, selector: #selector(didUnMount(_:)), name: NSWorkspace.didUnmountNotification, object: nil)
Capture mount and unmount events in:
@objc func didMount(_ notification: NSNotification) { if let devicePath = notification.userInfo!["NSDevicePath"] as? String { print(devicePath) } } @objc func didUnMount(_ notification: NSNotification) { if let devicePath = notification.userInfo!["NSDevicePath"] as? String { print(devicePath) } }
It will print the path to the device, for example, / Volumes / EOS_DIGITAL Here are the constants that you can read from userInfo.
NSDevicePath, NSWorkspaceVolumeLocalizedNameKey NSWorkspaceVolumeURLKey
mohacs
source share