cocoaudiddeviceid

How do I get device id in the Apple Cocoa application?


How do I get device id in Apple Cocoa application with swift 4.2?


Solution

  • You can get the Hardware UUID with IOKit

    func hardwareUUID() -> String?
    {
        let port: mach_port_t
        if #available(macOS 12.0, *) {
            port = kIOMainPortDefault // New name in macOS 12 and higher
        } else {
            port = kIOMasterPortDefault // Old name in macOS 11 and lower
        }
        let matchingDict = IOServiceMatching("IOPlatformExpertDevice")
        let platformExpert = IOServiceGetMatchingService(port, matchingDict)
        defer{ IOObjectRelease(platformExpert) }
    
        guard platformExpert != 0 else { return nil }
        return IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformUUIDKey as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as? String
    }