I have been learning about JSON parsing in SWIFT apps. So far I have been using a simple free API and had no issues, application worked as designed. But now I am calling an API that returns an array inside an array. I have read and prepared my variables to access the element as instructed, but still SWIFT does not see any data inside this returned JSON. I have been struggling with this for 2 days, changing all I can find online and think of, still my default variables are not being overwritten with the data from JSON. Using the pod SWIFTYJson.
JSON partial extract:
{
"list" : [
{
"main" : {
"grnd_level" : 984.67999999999995,
"temp_min" : 283.30000000000001,
"temp_max" : 284.54599999999999,
"temp" : 283.30000000000001,
"sea_level" : 1022.5,
"pressure" : 984.67999999999995,
"humidity" : 88,
"temp_kf" : -1.25
},
"clouds" : {
"all" : 0
},
"weather" : [
{
"main" : "Clear",
"icon" : "01n",
"description" : "clear sky",
"id" : 800
}
],
Code to handle it:
func getWeatherData(url: String, parameters: [String : String]){
//make http request and handle the JSON response
print("\(url)\(parameters)")
Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
response in //in means you are inside a closure (function inside a function)
if response.result.isSuccess {
print("Successfully got the weather data!")
let weatherJSON : JSON = JSON(response.result.value!) //saving the JSON response to a constant weathrJSON . We are using ! to self unwrap the value.
self.updateWeatherData(json: weatherJSON) //func to parse our json from API. Self tells the compiler to look for the method inside the current class
print(weatherJSON)
} else {
self.cityName.text = "Unable to fetch weather - please check active connection."
}
}
}
func updateWeatherData(json: JSON) {
(...)
//parse JSON for weather forecast day 1
weatherDataModel.weatherTest1 = json["list"][0]["weather"][0]["id"].intValue
//parse JSON for weather forecast day 2
weatherDataModel.weatherTest2 = json["list"][8]["weather"][0]["id"].intValue
//parse JSON for weather forecast day 3
weatherDataModel.weatherTest3 = json["list"][16]["weather"][0]["id"].intValue
print("TEST variable 1: \(weatherDataModel.weatherTest1)")
print("TEST variable 2: \(weatherDataModel.weatherTest2)")
print("TEST variable 3: \(weatherDataModel.weatherTest3)")
Variables printed to console remain unchanged from default values:
TEST variable 1: 0
TEST variable 2: 0
TEST variable 3: 0