I am trying to get a tree like structure of all volumes of my computer using Swift.
The simplest way to get all the mounted volumes is this code:
FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil)
Using this URL
, I can create a DADisk
object to get the BSD name:
if let session = DASessionCreate(kCFAllocatorDefault) {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, url as CFURL) {
if let bsdName = DADiskGetBSDName(disk) {
volume.bsdName = String(cString : bsdName) // Volume is my own class.
}
}
}
Now for the "main" disk, I get "disk0". I want to get additional information about this disk. If I take a look at the Disk Utility, disk0 does not seem to do much, so I want to get all of the "sub" volumes of disk0. I tried to gather all disks, cut "disk" and then parse the remains number. Sometimes this works (if disk1 has sub volumes disk1s1 and disk1s2), but sometimes there is a root disk (let's call it disk2) and there is one (virtual?) Container. Underneath this container, there are additional disks called disk3 and disk3s1 (this is where my approach fails).
I have tried using IOKit
which prints all the disk names. However, I don't know how to build the tree like structure (I suppose I could hack something based on the path):
var iterator: io_iterator_t = 0
let matching: CFDictionary = IOServiceMatching(kIOServicePlane)
IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator)
var child: io_object_t = IOIteratorNext(iterator)
while child != 0
{
if let bsdName = IORegistryEntryCreateCFProperty(child, self.bsdNameKey as CFString, kCFAllocatorDefault, IOOptionBits(kIORegistryIterateRecursively))
{
Swift.print(bsdName)
}
child = IOIteratorNext(iterator)
}
Is there a reliable way to get a main disk and all of its volumes in some sort of hierarchy?