Get user preferred temperature setting in macOS
Asked Answered
G

2

5

I'm trying to read the user set system preferences for Temperature unit (Celsius/Fahrenheit). I was trying to get this data using NSLocale but I cannot find any evidence of a temperature setting in there.

Is it even possible to read this data?

Thanks!

Gottfried answered 4/8, 2017 at 16:18 Comment(3)
Dupe: Determine user's “Temperature Unit” setting on iOS 10 (Celsius / Fahrenheit)Taunt
Possible duplicate of Determine user's "Temperature Unit" setting on iOS 10 (Celsius / Fahrenheit)Chromo
No duplicate as the linked question addresses iOS while this questions addresses macOSGottfried
T
4

The official API is documented under the 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")
}

If you wonder how I found it, I used the defaults utility in the Terminal:

> defaults find temperature
Found 1 keys in domain 'Apple Global Domain': {
    AppleTemperatureUnit = Fahrenheit;
}
Found 1 keys in domain 'com.apple.ncplugin.weather': {
    WPUseMetricTemperatureUnits = 1;
}
Tache answered 4/8, 2017 at 22:17 Comment(0)
K
3

This is a bit of a hack, but you can do it this way on macOS 10.12+ and 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

This outputs "F" in my playground which defaults to the US locale. But change your locale or use this code on a device and you'll get the locale specific temperature unit - or the string for it anyway.

Kulda answered 4/8, 2017 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.