Created
October 18, 2016 14:25
-
-
Save leogdion/77f6143ecf793e1ba381917d4b3b286c to your computer and use it in GitHub Desktop.
How To Get A Serial Number on macOS in Swift
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
var serialNumber: String? { | |
let platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice") ) | |
guard platformExpert > 0 else { | |
return nil | |
} | |
guard let serialNumber = (IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeUnretainedValue() as? String)?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) else { | |
return nil | |
} | |
IOObjectRelease(platformExpert) | |
return serialNumber | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is what I just was able to figure out to get working for me, granted I am brand new to figuring out Swift but I was able to get a serial number on a M2 chip when called with text(serialNumber).
`
var serialNumber: String {
let platformExpert = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOPlatformExpertDevice") )
guard platformExpert > 0 else {
return ""
}
guard let serialNumber = (IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeUnretainedValue() as? String)?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) else {
return ""
}
IOObjectRelease(platformExpert)
return serialNumber
}
`