This is a very simple example as starting point showing only the relevant data.
The example decodes the list
array into a custom struct. the dt
key is decoded into Date
. Then it creates a DateComponents
instance with noon in the current time zone and filters the dates.
struct WeatherData : Decodable {
let cod : String
let list : [List]
}
struct List : Decodable {
let dt : Date
}
let jsonString = """
{ "cod": "200", "message": 0.0054, "cnt": 40, "list": [{ "dt": 1525100400, "main": {"temp": 12.43, "temp_min": 10.44, "temp_max": 12.43, "pressure": 1015.9, "sea_level": 1035.33, grnd_level": 1015.9, "humidity": 64, "temp_kf": 1.99 }, "weather": [{"id": 800, "main": "Clear", "description": "clear sky", "icon": "01d"}], "clouds": {"all": 0}, "wind": {"speed": 4.66, "deg": 307.008},"sys": {"pod": "d"},"dt_txt": "2018-04-30 15:00:00"}]}
"""
let data = Data(jsonString.utf8)
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let result = try decoder.decode(WeatherData.self, from: data)
let utcDifference = TimeZone.current.secondsFromGMT() / 3600
let noonComponents = DateComponents(hour: 12 + utcDifference, minute: 0, second: 0)
let noonDates = result.list.filter { Calendar.current.date($0.dt, matchesComponents:noonComponents) }
print(noonDates)
} catch {
print("error:", error)
}
2
solved In a 5 day weather array how does one isolate a single time slot per day using swift?