从代码中确定卷是否为磁盘映像 (DMG)

Determine if a Volume is a Disk Image (DMG) from code

来自 Objective C(或 Swift),我需要确定安装的卷是否为磁盘映像(从 .dmg 文件安装)。

类似的问题让我找到了 NSURL Volume Property Keys,但其中 none 似乎给出了 type/protocol 的卷数。

但是,我可以通过 Protocol 下的终端 diskutil 功能看到此信息:

~/Temp$ diskutil info /dev/disk8
   Device Identifier:        disk8
   Device Node:              /dev/disk8
   Part of Whole:            disk8
   Device / Media Name:      Apple UDIF read-only Media

   Volume Name:              Not applicable (no file system)

   Mounted:                  Not applicable (no file system)

   File System:              None

   Content (IOContent):      GUID_partition_scheme
   OS Can Be Installed:      No
   Media Type:               Generic
   Protocol:                 Disk Image <=== THIS IS WHAT I WANT
   SMART Status:             Not Supported

   Total Size:               5.2 MB (5242880 Bytes) (exactly 10240 512-Byte-Units)
   Volume Free Space:        Not applicable (no file system)
   Device Block Size:        512 Bytes

   Read-Only Media:          Yes
   Read-Only Volume:         Not applicable (no file system)
   Ejectable:                Yes

   Whole:                    Yes
   Internal:                 No
   OS 9 Drivers:             No
   Low Level Format:         Not supported

编辑:找到 some code that at least used to do this, by means of this included category extension to NSWorkspace。但是,它是 ARC 之前的版本,我不确定它是否仍然有效。

通过 this partial answer 在其他问题上找到它..

您可以使用 DiskArbitration 框架获取此信息。要使用下面的示例,您必须 link 反对并 #import 它。

#import <DiskArbitration/DiskArbitration.h>

...

- (BOOL)isDMGVolumeAtURL:(NSURL *)url
{

  BOOL isDMG = NO;

  if (url.isFileURL) {

    DASessionRef session = DASessionCreate(kCFAllocatorDefault);
    if (session != nil) {

      DADiskRef disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, (__bridge CFURLRef)url);
      if (disk != nil) {

        NSDictionary * desc = CFBridgingRelease(DADiskCopyDescription(disk));
        NSString * model = desc[(NSString *)kDADiskDescriptionDeviceModelKey];
        isDMG = ([model isEqualToString:@"Disk Image"]);

        CFRelease(disk);

      }

      CFRelease(session);

    }

  }

  return isDMG;

}

用法:

BOOL isDMG = [someObject isDMGVolumeAtURL:[NSURL fileURLWithPath:@"/Volumes/Some Volume"]];

希望对您有所帮助。