Created
August 2, 2015 05:07
-
-
Save adgray/1f31526cc055e5d39864 to your computer and use it in GitHub Desktop.
Get Volume UUID for Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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