4

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!

Mike Nathas
  • 1,247
  • 2
  • 11
  • 29
  • Dupe: [Determine user's “Temperature Unit” setting on iOS 10 (Celsius / Fahrenheit)](https://stackoverflow.com/q/39727075/2415822) – JAL Aug 04 '17 at 16:48
  • 1
    Possible duplicate of [Determine user's "Temperature Unit" setting on iOS 10 (Celsius / Fahrenheit)](https://stackoverflow.com/questions/39727075/determine-users-temperature-unit-setting-on-ios-10-celsius-fahrenheit) – CRD Aug 04 '17 at 23:32
  • No duplicate as the linked question addresses iOS while this questions addresses macOS – Mike Nathas Aug 05 '17 at 06:35

2 Answers2

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;
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
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.

Abizern
  • 146,289
  • 39
  • 203
  • 257