2017-08-04 35 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」,默認爲美國語言環境。但是改變你的語言環境或者在設備上使用這個代碼,你會得到特定的語言環境單位 - 或者反正它的字符串。