Hi. I’m having a brain block right now and I can’t figure out how to display only 12 hours of hourly temperature rather than the 48 hours with the OpenWeatherMap API OneCall.
Here is my ViewModel
class WeatherModel: ObservableObject {
//Declare published property wrapper, that when the the property value changes, we want to notifty anyone who is observing it
@Published var weatherData: Weather?
@AppStorage("cityName") var cityName = ""
init(){
getWeatherData(cityName)
}
//Init method gets run when a new instance of WeatherModel is created
//MARK: - OpenWeatherMap API methods
func getWeatherData(_ cityName: String){
CLGeocoder().geocodeAddressString(cityName){(placemarks, error ) in
if let error = error {
print(error)
}
if let lat = placemarks?.first?.location?.coordinate.latitude,
let lon = placemarks?.first?.location?.coordinate.longitude {
//first is the first element of the collection
let weatherUrlString = "https://api.openweathermap.org/data/2.5/onecall?lat=\(lat)&lon=\(lon)&exclude=minutely,daily,alerts&units=imperial&appid=\(Constants.apiKey)"
let weatherUrl = URL(string: weatherUrlString)
guard weatherUrl != nil else {
return
}
let request = URLRequest(url: weatherUrl!)
//Create a URL session
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { data, response, error in
guard error == nil else {
return
}
do{
let decoder = JSONDecoder()
var result = try decoder.decode(Weather.self, from: data!)
//parsing the weather data into the constant, result
//Add UUId's to the hourly weather objects. Use the variable Result since that is parsing the weather
for i in 0..<result.hourly.count {
result.hourly[i].id = UUID()
}
DispatchQueue.main.async {
self.weatherData = result
}
}catch {
print(error)
}
}
dataTask.resume()
}
}
}//func getWeatherData
}
Model
struct Weather: Decodable {
var current: Current
var hourly: [Current]
//Hourly is an arrary of weather responses (i.e. Current). It parses the data because the arrary is similar to Current properties
}
struct Current: Decodable, Identifiable {
var id: UUID?
var dt: Double
var temp: Double
var feels_like: Double
var weather: [WeatherInfo]
}
struct WeatherInfo: Decodable {
var description: String
}
Right now this is just a rough view and will update the look of it but for now I’m putting it as a list
View
List(model.weatherData?.hourly ?? [] ) {
hour in
Text("\(Constants.dtConversion(hour.dt)), \(Constants.tempToString(hour.temp))")