Search code examples
iosjsonswiftweather-api

how to get data from Child JSON


I am making a weather app and I am trying to get the date and weather from my son file. I successfully get inside "daily" but I can't get inside "data" which is inside "daily". this is the code:

func downloadForecastWeather(completed: @escaping DownloadComplete) {
    Alamofire.request(FORECAST_API_URL).responseJSON { (response) in
        let result = response.result
        if let dictionary = result.value as? Dictionary<String, AnyObject> {
            if let list = dictionary["list"] as? [Dictionary<String, AnyObject>] {
                for item in list {
                    let forecast = ForecastWeather(weatherDict: item)
                    self.forecastArray.append(forecast)
                }
                self.forecastArray.remove(at: 0)
                self.tableView.reloadData()
            }
        }
        completed()
    }
}

and here is my ForecastWeather class:

init(weatherDict: Dictionary<String, AnyObject>) {
    if let temp = weatherDict["temperatureMin"] as? Double {

            let rawValue = (temp - 273.15).rounded(toPlaces: 0)
            self._temp = rawValue
        }


    if let date = weatherDict["time"] as? Double {

        let rawDate = Date(timeIntervalSince1970: date)
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium

        self._date = "\(rawDate.dayOfTheWeek())"
    }

}

Here is a link for json: https://api.darksky.net/forecast/132d3013b6e07bdf66159c1f5a90f76c/37.8267,-122.4233 So basically my question is how to get data from "data" which is inside "daily" and use it in my for in method.


Solution

  • Try using with SwiftyJSON it is easy to integrate in your code, all you have to do is to add below code inside your downloadForecastWeather function.

    func downloadForecastWeather(completed: @escaping DownloadComplete) {
            Alamofire.request(FORECAST_API_URL).responseJSON { (response) in
    
                let jsondata = JSON(response.result.value!)
    
                if let myData = jsondata["list"]["daily"]["data"].arrayObject { // here you can access your data inside daily
                    for data in myData {
                        let forecast = ForecastWeather(weatherDict: data)
                        self.forecastArray.append(forecast)
                    }
                    self.forecastArray.remove(at: 0)
                    self.tableView.reloadData()
                }
                completed()
            }
        }
    

    For more details please refer to this Documentation.

    I hope it works for you.

    : D