Last active
July 14, 2021 14:02
-
-
Save AndrewWCarson/28fa0d86be7c8c841b2c31d0ec6ddf57 to your computer and use it in GitHub Desktop.
Simple usage of the IOKit framework for macOS in Swift. Note: IOKit is not compatible with App Sandbox and is not suitable for the App Store.
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
// | |
// IOKit Discovery.swift | |
// | |
// Created by Andrew Worth Carson on 7/13/21. | |
// | |
import Foundation | |
import IOKit | |
enum CFType { | |
case bool | |
case string | |
case any | |
} | |
func convertCFUnmanaged(_ unmanaged: Unmanaged<AnyObject>, _ type: CFType) -> Any? { | |
switch type { | |
case .bool: | |
return convertCFUnmanagedToAny(unmanaged) as? Bool | |
case .string: | |
return convertCFUnmanagedToAny(unmanaged) as? String | |
default: | |
return convertCFUnmanagedToAny(unmanaged) | |
} | |
} | |
func convertCFUnmanagedToAny(_ unmanaged: Unmanaged<AnyObject>!) -> Any { | |
let value = Unmanaged<AnyObject>.fromOpaque(unmanaged.toOpaque()).takeUnretainedValue() as Any | |
return value | |
} | |
func registryEntry(platform: mach_port_t, service: String, key: String, type: CFType) -> Any? { | |
let ioPlatform = IOServiceGetMatchingService(0, IOServiceMatching(service)) | |
guard ioPlatform > 0 else { | |
return nil | |
} | |
guard let ioData = IORegistryEntryCreateCFProperty(ioPlatform, key as CFString, kCFAllocatorDefault, 0) else { | |
IOObjectRelease(ioPlatform) | |
return nil | |
} | |
IOObjectRelease(ioPlatform) | |
return convertCFUnmanaged(ioData, type) | |
} | |
func getSerialNumber() -> String { | |
return registryEntry(platform: kIOMasterPortDefault, service: "IOPlatformExpertDevice", key: kIOPlatformSerialNumberKey, type: .string) as! String | |
} | |
func isSolidState() -> Bool { | |
return registryEntry(platform: kIOMasterPortDefault, service: "X86PlatformPlugin", key: "BootDriveIsInternalSolidState", type: .bool) as! Bool | |
} | |
print("Serial number: \(getSerialNumber())") | |
print("Solid state: \(isSolidState())") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment