Skip to content

Instantly share code, notes, and snippets.

@leogdion
Created October 18, 2016 14:25
Show Gist options
  • Save leogdion/77f6143ecf793e1ba381917d4b3b286c to your computer and use it in GitHub Desktop.
Save leogdion/77f6143ecf793e1ba381917d4b3b286c to your computer and use it in GitHub Desktop.
How To Get A Serial Number on macOS in Swift
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
}
@leogdion
Copy link
Author

Great point @ccorbell
Would you use a defer statement in order to make sure it is released?

@WelkinDev
Copy link

thx~

@anoopmg
Copy link

anoopmg commented Oct 6, 2021

This one works fine in intel based mac, but failed in M1 mac.
Any idea about M1 mac

@codedeman
Copy link

it's bad thing it only works for ios 16

@sagar448
Copy link

Anyone have any idea for M1 chips or newer macs? Don't know if it works for newer macs

@ThatOneGuyGreggers
Copy link

ThatOneGuyGreggers commented Feb 8, 2023

Anyone have any idea for M1 chips or newer macs? Don't know if it works for newer macs

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
}
`

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