How do I obtain disk identifier in Swift

Use DiskArbitration.framework

At a high level, you can use the Disk Arbitration framework to:

  • Receive notification of disk-related events (disk ejection, for example) and participate in the arbitration process (preventing disk ejection, for example).
  • Obtain information about disks and manipulate disks (requesting that a disk be ejected, for example).

First create a global session with DASessionCreate, then create a disk reference with DADiskCreateFromVolumePath for each mounted volume and get the BSD name (identifier) with DADiskGetBSDName. Convert the C-string to String and you are done.

if let session = DASessionCreate(kCFAllocatorDefault) {
    let mountedVolumeURLs = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil)!
    for volumeURL in mountedVolumeURLs {
        if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volumeURL as CFURL),
            let bsdName = DADiskGetBSDName(disk) {
            let bsdString = String(cString : bsdName)
            print(volumeURL.path, bsdString)
        }
    }
}

Another suitable way is to parse IORegistry.

Tags:

Macos

Swift