2016-07-05 3 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

- 아이폰 OS 10/맥 OS 시에라, 애플의로를 는 현지화뿐만 아니라 전환을 처리하는 Foundation에 Measurements and Units 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) 
} 
관련 문제