I have an OS X application that needs to respond to a volume being mounted or unmounted.
I've already solved this problem by retrieving the list of volumes periodically and checking for changes, but I'd like to know if there is a better way.
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 device path e.g /Volumes/EOS_DIGITAL Here are the constants you can read from userInfo.
NSDevicePath,
NSWorkspaceVolumeLocalizedNameKey
NSWorkspaceVolumeURLKey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With