Temperature was not able to be retrieved

0

I am building a simple macOS menu bar app in swift that displays my machine's CPU temperature and I'm just testing out my function to make sure it can retrieve the temp and display it in the Xcode terminal but instead my error handler messages are triggered indicating an issue retrieving my machines CPU temp data

"CPU temp °F could not be retrieved temps couldnot be displayed"

import Cocoa
import IOKit
import IOKit.ps


class CPUTempWithServiceMatching {
    
    static func getCPUTemp() -> Double? {
        
        let dictionaryMatching = IOServiceMatching("AppleSMC")
        
        var service = IOServiceGetMatchingService(kIOMainPortDefault, dictionaryMatching)
        
        var temp = "0.0"
        
        if service != 0 {
            
            let key = "TC0P"   //thermal zone zero proxy
            
            if let result = IORegistryEntryCreateCFProperty(service, key as CFString, kCFAllocatorDefault, 0 ) {
                temp = (result.takeUnretainedValue() as! NSNumber).doubleValue.description
                IOObjectRelease(service)
                
                if let CPUTemp = Double(temp) {
                    print("CPU Temp: \(CPUTemp) °F")
                    return(CPUTemp)
                }
            }
            print("CPU temp °F could not be retrieved")
        }
        return nil
    }
}
  @main
struct program {
   static func main() {
        if let cpuTemp = CPUTempWithServiceMatching.getCPUTemp() {
            print("cpu temp\(cpuTemp) °F")
        } else {
            print("temps couldnot be displayed")
        }
    }
}

There is no supported mechanism for getting CPU temperature. Reading undocumented I/O registry properties is unlikely to work in the long term. See this post for more background on that.

We do support folks getting the device’s thermal conditions so that their apps can adapt to that. If you’re getting the CPU temperature for that reason, check out the thermalState property.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Temperature was not able to be retrieved
 
 
Q