Determine user's “Temperature Unit” setting on iOS 10 (Celsius / Fahrenheit)

后端 未结 5 1329
既然无缘
既然无缘 2020-12-06 05:49

iOS 10 adds the ability for the user to set their \"Temperature Unit\" choice under Settings > General > Language & Region > Temperature Unit.

How can my app pro

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 06:22

    This seems to be a late answer, but I found a neat solution mentioned by @fábio-oliveira in the comments here.

    The original Apple thread: https://forums.developer.apple.com/thread/70258

    What I'm trying to do in my solution is to have a function to convert Kelvin temperature (parsed from JSON file and can be any temperature) into a temperature format dictated by Systems Locale or set by a user in Settings > General > Langauge & Region > Temperature Unit. However, I also need the temperature to display 0 digits after the decimal separator.

    So here's a Swift 4 solution (kelvin is the input temperature unit):

    func temperatureFormatter(kelvinTemp: Double) -> String{
            let mf = MeasurementFormatter()
            mf.numberFormatter.maximumFractionDigits = 0
            let t = Measurement(value: kelvinTemp, unit: UnitTemperature.kelvin)
            return (String(format:"%@", mf.string(from: t)))
        }
    

    And here you can call your function to convert the values (_currentTemp is your extracted JSON temperature value & convertedTemp is your resulting converted temperature based on conditions mentioned above):

    convertedTemp = temperatureFormatter(kelvinTemp: _currentTemp)
    

    Let me know if this solution works for you, it does work for me though. Thank you!

提交回复
热议问题