【问题标题】:Get user preferred temperature setting in macOS在 macOS 中获取用户首选的温度设置
【发布时间】:2018-01-12 16:00:44
【问题描述】:

我正在尝试读取用户设置的温度单位(摄氏度/华氏度)的系统首选项。 我试图使用 NSLocale 获取这些数据,但我找不到任何温度设置的证据。

甚至可以读取这些数据吗?

谢谢!

【问题讨论】:

标签: swift xcode cocoa foundation temperature


【解决方案1】:

官方 API 记录在Preferences Utilities

let key = "AppleTemperatureUnit" as CFString
let domain = "Apple Global Domain" as CFString

if let unit = CFPreferencesCopyValue(key, domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? String {
    print(unit)
} else {
    print("Temperature unit not found")
}

如果您想知道我是如何找到它的,我在终端中使用了 defaults 实用程序:

> defaults find temperature
Found 1 keys in domain 'Apple Global Domain': {
    AppleTemperatureUnit = Fahrenheit;
}
Found 1 keys in domain 'com.apple.ncplugin.weather': {
    WPUseMetricTemperatureUnits = 1;
}

【讨论】:

    【解决方案2】:

    这有点小技巧,但您可以在 macOS 10.12+ 和 iOS 10+ 上这样做:

    // Create a formatter.
    let formatter = MeasurementFormatter()
    
    // Create a dummy temperature, the unit doesn't matter because the formatter will localise it.
    let dummyTemp = Measurement(value: 0, unit: UnitTemperature.celsius)
    
    let unit = formatter.string(from: dummyTemp).characters.last // -> F
    

    这会在我的 Playground 中输出“F”,默认为美国语言环境。但是更改您的语言环境或在设备上使用此代码,您将获得特定于语言环境的温度单位 - 或者它的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多