Detect when volume is set to OS X

I have an OS X application that should respond to one that is mounting or unmounting.

I already solved this problem by periodically getting a list of volumes and checking for changes, but I would like to know if there is a better way.

+7
source share
4 answers

Register at the notification center that you receive from [[NSWorkspace sharedWorkspace] notificationCenter] , and then process the notifications that interest you. These are scope related: NSWorkspaceDidRenameVolumeNotification , NSWorkspaceDidMountNotification , NSWorkspaceWillUnmountNotification and NSWorkspaceDidUnmountNotification .

+10
source

The NSWorkspace approach is exactly what I was looking for. A few lines of code later, I have a much better solution than using a timer.

 -(void) monitorVolumes { [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector: @selector(volumesChanged:) name:NSWorkspaceDidMountNotification object: nil]; [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector: @selector(volumesChanged:) name:NSWorkspaceDidUnmountNotification object:nil]; } -(void) volumesChanged: (NSNotification*) notification { NSLog(@"dostuff"); } 
+15
source

Do you know SCEvents ? This allows you to be notified of changes in the contents of the monitored folder ( /Volumes ). Thus, you do not need to use a timer to periodically check the content.

+2
source

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 
+2
source

All Articles