2016-07-05 144 views
1

我試圖從用戶當前位置檢索溫度。將開爾文轉換爲Swift中的攝氏溫度

我使用OpenWeatherMap中的API。問題是,它們提供的溫度默認爲開爾文,我希望以攝氏度計。

我知道我只需要從開爾文值中減去273.15 ....?但我正在努力弄清楚在哪裏做到這一點。

我的設置我的標籤代碼:

var jsonData: AnyObject? 

func setLabels(weatherData: NSData) { 

    do { 

     self.jsonData = try NSJSONSerialization.JSONObjectWithData(weatherData, options: []) as! NSDictionary 

    } catch { 
     //handle error here 

    } 

    if let name = jsonData!["name"] as? String { 

     locationLabel.text = "using your current location, \(name)" 

    } 

    if let main = jsonData!["main"] as? NSDictionary { 
     if let temperature = main["temp"] as? Double { 

      self.tempLabel.text = String(format: "%.0f", temperature) 

     } 

    } 

} 

誰能幫我得到這個權利,請,因爲我真的不知道從哪裏開始,謝謝。

讓我知道你是否需要查看我的更多代碼。

+0

僅供參考 - 隨着iOS的10/MacOS的塞拉利昂,蘋果已將基準測量和單位API引入,以處理您的轉換以及本地化。鏈接到文檔:https://developer.apple.com/reference/foundation/nsmeasurement以及免費的WWDC視頻:https://developer.apple.com/videos/play/wwdc2016/238/ –

回答

7
if let kelvinTemp = main["temp"] as? Double { 
    let celsiusTemp = kelvinTemp - 273.15 
    self.tempLabel.text = String(format: "%.0f", celsiusTemp) 
} 

或者乾脆

self.tempLabel.text = String(format: "%.0f", temperature - 273.15) 
1

從上面的代碼,在我看來,正確的地點做你得到的溫度

if let temperatureInKelvin = main["temp"] as? Double { 
    let temperatureInCelsius = temperatureInKelvin - 273.15 
    self.tempLabel.text = String(format: "%.0f", temperature) 
} 

後,在未來,雖然這將是正確的,我可能會解析你的JSON值在一個單獨的類中,並將它們存儲在模型對象中,稍後可以調用它。

1

這裏:

self.tempLabel.text = String(format: "%.0f", temperature - 273.15) 

,或者你可以在這裏做(僞語法我不知道斯威夫特那麼好):

if let temperature = (main["temp"] as? Double) - 273.15 { 
    self.tempLabel.text = String(format: "%.0f", temperature) 
}