Pablo Duque
Pablo Duque

Reputation: 383

Parsing JSON from OpenWeatherMap in Swift

I've got the connection to work, but I cant manage to get the description from weather Array. Because it is a Dictionary inside an Array.

{"weather":
[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}]}

Getting the temperature works fine like this:

if let main = item["main"] as? NSDictionary {
            println("Main existe")
            if let temp = main["temp"] {
                println("Temp existe")
                weatherRequested.append(temp.stringValue)
            }
        }

Upvotes: 1

Views: 1797

Answers (3)

Pablo Duque
Pablo Duque

Reputation: 383

I ended up working out a solution:

 if let item = jsonResult as? NSDictionary {

        if let weather = item["weather"] as? NSArray{
            if let value = weather[0] as? NSDictionary{
                if let description = value["description"] as? String{
                    weatherRequested.append(description)
                }
            }
        }
        if let main = item["main"] as? NSDictionary {
            if let temp = main["temp"] {
                weatherRequested.append(temp.stringValue)
            }
        }
    }

Thanks for anyone who tried to help me anyways! :)

Upvotes: 2

Manuel
Manuel

Reputation: 1695

You have a mistake in

if let item = jsonResult[0] as? NSDictionary {

jsonResult is an NSDictionary not an Array. Delete "[0]" and try again

Upvotes: 0

mohonish
mohonish

Reputation: 1396

The default JSON parsing in iOS with Swift is plain bad. I would suggest you to use SwiftyJSON library. That would make parsing it as easy as...

let result = JSON(jsonResult)
let weatherDesc = result["weather"]["description"].stringValue
let weatherTemp = result["main"]["temp"].stringValue

Hope that helps!

Upvotes: 3

Related Questions