0

I am working on a weather app that parses JSON data and sets the text of my label to the temp value of the JSON request. I got the value of id from the weather object array, but the temp is not in an array it is just an object. Can someone please tell me where I am wrong. My value is reurning nil because I am not fetching it correctly. Here is my snippet and JSON.

@IBAction func getWeather(sender: AnyObject) {
        let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=MYAPPID")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                print("JSON Downloaded Sucessfully.")

                do{

                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                    if let today = json["weather"] as? [[String: AnyObject]] {
                        //this is pulling 4 key value pairs
                        for weather in today {

                            //this works
                            let id = weather["id"]?.stringValue
                            self.trumpDescription.text=id;
                            print(id)

                            //this is where I am confused it changes from an array to just an object
                            let temp = json["temp"] as? String
                            self.currentTempView.text=temp;
                            print(temp)
                        }

                    }

                }

                catch {
                    print("Error with Json: \(error)")
                }

            }
        }

        task.resume()
    }`

Here is the JSON:

{
    "coord": {
    "lon": 138.93,
    "lat": 34.97
    },
    "weather": [
    {
    "id": 803,
    "main": "Clouds",
    "description": "broken clouds",
    "icon": "04n"
    }
    ],
    "base": "cmc stations",
    "main": {
    "temp": 292.581,
    "pressure": 1019.48,
    "humidity": 99,
    "temp_min": 292.581,
    "temp_max": 292.581,
    "sea_level": 1028.92,
    "grnd_level": 1019.48
    },
    "wind": {
    "speed": 5.36,
    "deg": 237.505
    },
    "clouds": {
    "all": 64
    },
    "dt": 1464964606,
    "sys": {
    "message": 0.0037,
    "country": "JP",
    "sunrise": 1464895855,
    "sunset": 1464947666
    },
    "id": 1851632,
    "name": "Shuzenji",
    "cod": 200
    }
3
  • The value for temp is in an object. jsonlint.com Commented Jun 3, 2016 at 14:53
  • temp is not in weather ... its an object of main Commented Jun 3, 2016 at 15:02
  • take a look at this, generated model for openweathermap It might save you some time. Commented Jun 4, 2016 at 14:47

2 Answers 2

3

It looks like it should be

if let main = json["main"] as? NSDictionary {
    let temp = main["temp"] as! String
    print(temp)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to your example I now understand the logic. Thank you.
0

Instead of this:
let temp = json["temp"] as? String

Try this:

if let main = json["main"] as? [String: AnyObject] {
    let temp = main[temp]?.stringValue
    print(temp)

    //alternatively you can try this as per your convenience of data type
    let tempNew = main[temp]?.doubleValue
    print(tempNew) 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.