苹果系统.如何以编程方式获取CPU温度

Un *_* Ny 1 macos iokit swift

我需要用斯威夫特CPU温度,但我不能找到除了任何信息.

我认为我应该使用IOKit.framework,但是没有太多关于它的信息.

Dav*_* S. 7

使用https://github.com/lavoiesl/osx-cpu-temp/blob/master/smc.c我得到了它的工作.你必须做一些事情:

简化main()其他事情:

double calculate()
{
    SMCOpen();
    double temperature = SMCGetTemperature(SMC_KEY_CPU_TEMP);
    SMCClose();
    temperature = convertToFahrenheit(temperature);
    return temperature;
}
Run Code Online (Sandbox Code Playgroud)

写一个ObjC包装器:

#import "SMCObjC.h"
#import "smc.h"   
@implementation SMCObjC

+(double)calculateTemp {
    return calculate();
}

@end
Run Code Online (Sandbox Code Playgroud)

将标头添加到Swift桥接标头中.

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "SMCObjC.h"
Run Code Online (Sandbox Code Playgroud)

如果应用程序是沙盒,请为AppleSMC添加安全性豁免:

<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-only</key>
    <true/>
    <key>com.apple.security.temporary-exception.sbpl</key>
    <array>
        <string>(allow iokit-open)</string>
        <string>(allow iokit-set-properties (iokit-property &quot;AppleSMC&quot;))</string>
        <string>(allow mach-lookup (global-name &quot;com.apple.AssetCacheLocatorService&quot;))</string>
    </array>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)

从Swift中调用它.

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let temp = SMCObjC.calculateTemp()
        print("I got \(temp) in swift")
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的示例项目:

https://www.dropbox.com/sh/lpe9bm08s2ynoob/AAA-N_br7aqRxJRks53FYK0fa?dl=0