Search code examples
swiftuilabelopenweathermap

How do I add a degree symbol as part of a UILabel in iPhone development?


I have added the degree symbol to my UILabel but when the app runs it disappears. I am creating a weather app so it is important that it is formatted correctly. This is the code I have once the ViewController has loaded.

 override func viewDidLoad() {
    super.viewDidLoad()
    cityLabel.text = city
    userEnteredNewCityName(city: city)
    // Do any additional setup after loading the view.
}

Here is the code that updates the ViewController

func updateWeatherData(json: JSON) {
    if let tempResult = json["main"]["temp"].double {
        weatherDataModel.temperature = Int(tempResult - 273)
        weatherDataModel.city = json["name"].stringValue
        weatherDataModel.condition = json["weather"][0]["id"].intValue
        weatherDataModel.weatherIconName = weatherDataModel.updateWeathericon(condition: weatherDataModel.condition)

        updateUIWithWeatherData()
    } else {
        cityLabel.text = "No data available"
    }

}

func userEnteredNewCityName(city: String){
    let params : [String : String] = ["q" : city, "appid" : APP_ID]
    getWeatherData(url: WEATHER_URL, parameters: params)
}

 //Write the updateUIWithWeatherData method here:


func updateUIWithWeatherData() {
    cityLabel.text = weatherDataModel.city
    temperatureLabel.text = String(weatherDataModel.temperature)
    weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}

Any help would be appreciated.enter image description here


Solution

  • Ideally, use MeasurementFormatter:

    let measurement = Measurement(value: weatherDataModel.temperature, unit: UnitTemperature.celsius)
    
    let measurementFormatter = MeasurementFormatter()
    measurementFormatter.unitStyle = .short
    measurementFormatter.numberFormatter.maximumFractionDigits = 0
    measurementFormatter.unitOptions = .temperatureWithoutUnit
    
    temperatureLabel.text = measurementFormatter.string(from: measurement)   
    

    No need to convert to Int. The formatter will handle displaying of decimal digits.

    As a bonus, you don't have to do the Kelvin to Celsius conversion by yourself:

    let measurementInKelvin = Measurement(value: weatherDataModel.temperature, unit: UnitTemperature.kelvin)
    let measurement = measurementInKelvin.converted(to: .celsius)