2017-08-04 33 views
3

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

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

谢谢!

+0

杜佩:确定用户的“温度(Celsius/Fahrenheit)](https://stackoverflow.com/q/39727075/2415822) – JAL

+1

[确定iOS 10(摄氏/华氏)]上用户的“温度单位”设置(https) ://stackoverflow.com/questions/39727075/determi ne-users-temperature-unit-setting-on-ios-10-celsius-fahrenheit) – CRD

+0

没有重复,因为链接的问题解决了iOS问题,而这个问题解决了macOS –

回答

4

官方的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 

这在我的游乐场输出“F”,默认为美国语言环境。但是改变你的语言环境或者在设备上使用这个代码,你会得到特定的语言环境单位 - 或者反正它的字符串。