Search code examples
diskmountnsworkspace

cocoa how to get the ALREADY mounted unmountable disk


NSWorkspaceDidMountNotification works well to get the information of just mounted disk. But how can I get the information of already mounted disks before my app start?

command line: "diskutil list" and "diskutil info /" works but there should be a simple programmatically method there.

searched result of "DiskArbitration" or "VolumeToBSDNode example" don't work, IOkit difficult.

BTW, anyone recommend of using this? [NSWorkspace getFileSystemInfoForPath:isRemovable:isWritable:isUnmountable:description:type:]


Solution

  • How about [NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:]?

    Edit: Here's a snippet of code for how to use this to get removable drives and their volume names.

    NSArray *keys = [NSArray arrayWithObjects:NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, nil];
    NSArray *urls = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:keys options:0];
    for (NSURL *url in urls) {
      NSError *error;
      NSNumber *isRemovable;
      NSString *volumeName;
      [url getResourceValue:&isRemovable forKey:NSURLVolumeIsRemovableKey error:&error];
      if ([isRemovable boolValue]) {
        [url getResourceValue:&volumeName forKey:NSURLVolumeNameKey error:&error];
        NSLog(@"%@", volumeName);
      }
    }