🍁

Swift: macのバッテリー温度を取得する

2020/11/04に公開
import IOKit

func temperature() -> Double {
    let service: io_service_t = IOServiceGetMatchingService(
        kIOMasterPortDefault,
        IOServiceNameMatching("AppleSmartBattery")
    )
    let prop = IORegistryEntryCreateCFProperty(
        service,
        NSString(string: "Temperature") as CFString,
        kCFAllocatorDefault,
        0
    )
    let _ = IOObjectRelease(service)
    guard let value = prop?.takeUnretainedValue(),
          let temp = value as? Double
    else { return 0.0 }
    return temp / 100.0
}

Swift.print(temperature())

Discussion