Skip to content

Instantly share code, notes, and snippets.

@leogdion
Created October 18, 2016 14:25
Show Gist options
  • Select an option

  • Save leogdion/77f6143ecf793e1ba381917d4b3b286c to your computer and use it in GitHub Desktop.

Select an option

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
}
@Verurteilt
Copy link
Copy Markdown

It works perfectly! thank you so much!

@ccorbell
Copy link
Copy Markdown

I've seen this code in a couple of searches for Swift examples of doing this (I've previously done it in Obj-C) - I'm concerned about the guard return at line 9, I think you're skipping a call to IOObjectRelease(platformExpert) by returning there. If platformExpert is valid it should be released, even if the call to get the serial number returns nil.

@leogdion
Copy link
Copy Markdown
Author

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

@WelkinDev
Copy link
Copy Markdown

thx~

@anoopmg
Copy link
Copy Markdown

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
Copy Markdown

it's bad thing it only works for ios 16

@sagar448
Copy link
Copy Markdown

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

@ThatOneGuyGreggers
Copy link
Copy Markdown

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

@laike9m
Copy link
Copy Markdown

laike9m commented Feb 23, 2025

@anoopmg it works on ARM chips for me

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