I am trying to make weather app for a project and I am using openweathermap for my api. I got it to output some information but I can't figure out how to get the rest of the information. This is what comes out when I put it into Postman. How can I grab the info that is in {}, like the temp and the min and max temp? I know I can loop through it if it was an array but it's not.

So far I have tried to loop through it like an array and that didn't work:

if let mainJson = jsonObject["main"] as? [[String:AnyObject]]
{
    for eachtemp in mainJson
    {
        if let temp = eachtemp["temp"] as? String
        {
            print("the temp is: ", temp)
        }
    }
}

This is the response from the api:

{
    "coord": {
        "lon": -88.75,
        "lat": 41.93
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 281.24,
        "pressure": 1019,
        "humidity": 52,
        "temp_min": 279.26,
        "temp_max": 283.15
    },
    "visibility": 16093,
    "wind": {
        "speed": 7.7,
        "deg": 280,
        "gust": 11.3
    },
    "clouds": {
        "all": 1
    },
    "dt": 1555176309,
    "sys": {
        "type": 1,
        "id": 5706,
        "message": 0.0073,
        "country": "US",
        "sunrise": 1555154275,
        "sunset": 1555201965
    },
    "id": 420012399,
    "name": "Aurora",
    "cod": 200
}

1 Answers

0
vadian On Best Solutions

{} is a dictionary (Swift type [String:Any], never [String:AnyObject]), you have to get each value with key subscription, all requested values are Double

if let main = jsonObject["main"] as? [String:Any] {
    let temp = main["temp"] as! Double
    let tempMin = main["temp_min"] as! Double
    let tempMax = main["temp_max"] as! Double
    print(temp, tempMin, tempMax)
}

Regarding force unwrapping: openweathermap sends very reliable data. If main exists the keys inside exist, too


With Decodable it's much easier

struct WeatherAPI : Decodable {

    let main: Main

    struct Main : Decodable {
        let temp, tempMin, tempMax : Double
    }
}

let apiKey = ....

let url = URL(string:"http://api.openweathermap.org/data/2.5/weather?....." + apiKey)!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let error = error { print(error); return }
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let result = try decoder.decode(WeatherAPI.self, from: data!)
        print(result.main.temp, result.main.tempMin, result.main.tempMax)
    } catch {
        print(error)
    }
}
task.resume()