Dumitru Rogojinaru Dumitru Rogojinaru - 1 month ago 9
iOS Question

Parsing JSON with Alamofire Problems

I am new to swift and in programming, and I am trying to parse a JSON with the help of Alamofire and SwiftyJSON, if the JSON file is simple, I have no problems and working good, but when I have something like Dictionary -> Dictionary -> Array -> Dictionary, problems begin, so I have the following code:

func performCYesterdayWeatherFetch(forSelectedCity: String)
{
let properString = forSelectedCity.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
Alamofire.request("http://api.apixu.com/v1/history.json?key=MY_KEY&q=\(properString!)&dt=2016-10-20").responseJSON { (response) -> Void in
guard response.result.isSuccess else
{
print("Error while fetching remote rooms: \(response.result.error)")
return
}

guard let json = response.result.value as? JSON,
let forecastJson = json["forecast"].dictionary else
{
print("YESTERDAY PROBLEM")
return
}
for item in (forecastJson["forecastday"]?.arrayValue)!
{
let day = item["day"].dictionaryObject
guard let yesterdayTempCels = day?["avgtemp_c"] as! Double?,
let yesterdayTempFahr = day?["avgtemp_f"] as! Double? else
{
return

}


MY_KEY - is really my key, the problem is not in that i didn't input the key.

It always get in else here:

guard let json = response.result.value as? JSON,
let forecastJson = json["forecast"].dictionary else
{
print("YESTERDAY PROBLEM")
return
}


They result JSON looks like that:
The thin I need is avgtemp_c and avgtemp_f

JSON PIC

What am I doing wrong?

Answer

Here you have a solution where you don't even need SwiftyJSON to get those values.

let properString = forSelectedCity.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
Alamofire.request("http://api.apixu.com/v1/history.json?key=MY_KEY&q=\(properString!)&dt=2016-10-20").responseJSON { (response) -> Void
    guard let json = response.result.value as? [String: Any],
        let forecastDictionary = json["forecast"] as? [String: Any],
        let forecastDayArray = forecastDictionary["forecastday"] as? [[String: Any]] else {
            print("YESTERDAY PROBLEM")
            return
    }

    for item in forecastDayArray {
        guard let day = item["day"] as? [String: Any],
            let yesterdayTempCels = day["avgtemp_c"] as? Double,
            let yesterdayTempFahr = day["avgtemp_f"] as? Double else {
                return
        }

        // Here you should have the values that you need
    }
}
Comments