-
-
Save leogdion/77f6143ecf793e1ba381917d4b3b286c to your computer and use it in GitHub Desktop.
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 | |
} |
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.
Great point @ccorbell
Would you use a defer
statement in order to make sure it is released?
thx~
This one works fine in intel based mac, but failed in M1 mac.
Any idea about M1 mac
it's bad thing it only works for ios 16
Anyone have any idea for M1 chips or newer macs? Don't know if it works for newer macs
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
}
`
It works perfectly! thank you so much!