Search code examples
iosswiftswift2alamofireswifty-json

How to get the JSON data


I want to make an app that calls the API of forecast.io to get weather in my app. Someone said me to use SwiftyJSON and Alamofire . I'm new to programming and this is my first app so I don't really know how to do it right. That's my code for now , but I don't know if it is right or not , it works but the call isn't made and I need to enter the JSON data to get the "temperature" data:

// Get Weather
let URL = "https://api.forecast.io/forecast/apikey/\(lat),\(long)"
Alamofire.request(.GET, URL, parameters: nil)
    .responseJSON { response in
        let jsonData: AnyObject?
        do {
            jsonData = try NSJSONSerialization.JSONObjectWithData(response.data!, options: [])
        } catch  {                                                               
            
        }            
}

It only says that "jsonData" was never used. That's all I wrote for getting the call.


Solution

  • Once you have the jsonData variable, you can use it like a regular NSDictionary by putting the following lines in the do block after the first line

    guard let jsonDict = jsonData as? NSDictionary else {return}
    

    If you want to get the current forecast, all you have to do is

    guard let currentForecast = jsonDict["currently"] as? NSDictionary else {return}
    

    And then you can get its properties using this link

    guard let temperature = currentForecast["apparentTemperature"] as? Int else {return}
    

    All in all, your code should look something like this

    let URL = "https://api.forecast.io/forecast/apikey/\(lat),\(long)"
    Alamofire.request(.GET, URL, parameters: nil)
        .responseJSON { response in
            let jsonData: AnyObject?
            do {
                jsonData = try NSJSONSerialization.JSONObjectWithData(response.data!, options: [])
                guard let jsonDict = jsonData as? NSDictionary else {return}
                guard let currentForecast = jsonDict["currently"] as? NSDictionary else {return}
                guard let temperature = currentForecast["apparentTemperature"] as? Int else {return}
                print(temperature)
            } catch  {
                //TODO: Handle errors
            }
    }
    

    The catch block is to handle errors, so if it could not parse the JSON that's where you would display an alert saying that there was an error.