Skip to content

Instantly share code, notes, and snippets.

@adgray
Created August 2, 2015 05:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adgray/1f31526cc055e5d39864 to your computer and use it in GitHub Desktop.
Save adgray/1f31526cc055e5d39864 to your computer and use it in GitHub Desktop.
Get Volume UUID for Path
import DiskArbitration
func volumeUUIDForPath(path: String) -> String?
{
var retval: String?
if let session = DASessionCreate(kCFAllocatorDefault)
{
let fsStats = UnsafeMutablePointer<statfs>.alloc(1)
defer { fsStats.destroy(1) }
if statfs((path as NSString).UTF8String, fsStats) == 0
{
let deviceName = withUnsafePointer(&fsStats.memory.f_mntfromname,
{
(ptr) -> String? in
let int8Ptr = unsafeBitCast(ptr, UnsafePointer<Int8>.self)
return String.fromCString(int8Ptr)
})
if let device = deviceName,
disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, device),
description = DADiskCopyDescription(disk)
{
let myDict = description as NSDictionary
let uuid = myDict[kDADiskDescriptionVolumeUUIDKey as String /* "DAVolumeUUIDD" */] as! CFUUID
retval = CFUUIDCreateString(kCFAllocatorDefault, uuid) as String
}
else { retval = "" }
}
}
return retval
}
@adgray
Copy link
Author

adgray commented Aug 2, 2015

I needed a way to get the volume UUID of a file in Swift. Given a path, it will return nil (the path isn't valid), an empty string (the path is probably on a network share) or the volume's UUID (as returned by "diskutil info").

Working at commit time on OS X 10.10.4, Swift 2.0, Xcode 7 beta 4.

This code was inspired by some of https://github.com/baron/polkit/blob/master/FileSystem/DiskWatcher.m

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment