Detect volume mount and get its path

339 views Asked by At

I need to detect when a volume is mounted in OS X and also get its full path.

I have successfully implemented code which detects when a volume is mounted, however, getting its path is something I'm still struggling with.

The code to detect when a volume is mounted looks like this:

-(void) monitorVolumes
{
    // Notification for Mountingthe USB device

    [[[NSWorkspace sharedWorkspace] notificationCenter]addObserver:self selector: @selector(onVolumeMount:)
      name: NSWorkspaceDidMountNotification object: nil];

    // Notification for Un-Mountingthe USB device

    [[[NSWorkspace sharedWorkspace] notificationCenter]addObserver:self selector: @selector(onVolumeMount:)
      name: NSWorkspaceDidUnmountNotification object: nil];

}

-(void) onVolumeMount: (NSNotification*) notification
{
    NSLog(@"Volume Mount");

   //Code to get path here...
}

-(void) onVolumeUnmount: (NSNotification*) notification
{
    NSLog(@"Volume Unmount");
}

I am lost on how to properly get the path.

How can this be achieved?

1

There are 1 answers

0
Ken Thomases On BEST ANSWER

In the notification's userInfo dictionary, under the key NSWorkspaceVolumeURLKey, you'll find an NSURL for the volume. If you really need a path string, you can ask that NSURL for its path.

NSString* path = [notification.userInfo[NSWorkspaceVolumeURLKey] path];