macoscocoacore-foundationdiskarbitration

How do I get notification of a drive being powered on?


I have a problem on OS X, where if a drive is plugged in while powered off, and then powered on, I don't receive notification that a new disk has appeared. I do receive notification if I plug in a drive that is already powered on.

Currently, I'm registering callbacks for when a disk appears, disappears, or the description changes via disk arbitration (DARegisterDiskAppearedCallback et al). I don't see any other callbacks that might cover the scenario of a drive being turned on.

How do I receive notification when a drive that is already plugged in gets powered on?


Solution

  • NSWorkspace provides a notification, NSWorkspaceDidMountNotification, when a disk is mounted. In outline you declare a notification handler, for example:

    - (void) mountNotify:(NSNotification *)notification
    {
       // extract details from notification
       NSDictionary *userInfo = notification.userInfo;
       NSString *volumeMounted = userInfo[@"NSDevicePath"];
       NSString *volumeDisplayName = userInfo[@"NSWorkspaceVolumeLocalizedNameKey"];
    
       if (volumeMounted != nil)
       {
           // volume has been mounted
       }
    }
    

    and register for notifications:

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

    There is also a similar notification, NSWorkspaceDidUnmountNotification, for when a disk is unmounted.

    For more details see Apple's NSWorkspace documentation.

    HTH.