I'm new to swift and I'm working on a weather app that requests the data from darksky.net API, I've managed to send the request and receive the json response, however darksky returns all of the weather data (current weather, hourly weather and daily weather) in one json file response.
I'm trying to parse the data into different classes without the need to start a new request everytime. How can I achieve that?
Should this json respone be stored somewhere? Is there a way to pass it between (model)classes without starting a new request?
I have tried creating a networking class that requests the json, and stores it in an JSON object, however, whenever I start an instant of that class, it will fire the request again.
import Foundation
import Alamofire
import SwiftyJSON
class CurrentWeather {
private var _date: Date!
private var _currentTemp: Double!
private var _feelsLike: Double!
var date: Date {
if _date == nil {
_date = Date()
}
return _date
}
var currentTemp: Double {
if _currentTemp == nil {
_currentTemp = 0.0
}
return _currentTemp
}
var feelsLike: Double {
if _feelsLike == nil {
_feelsLike = 0.0
}
return _feelsLike
}
func getCurrentWeather(completion: @escaping(_ success: Bool) -> Void) {
let LOCATIONAPI_URL = "https://api.darksky.net/forecast/0123456789abcdef9876543210fedcba/42.3601,-71.0589"
// request JSON from url, using Alamofire Library
Alamofire.request(LOCATIONAPI_URL).responseJSON { (response) in
let result = response.result
// check if respose is valid
if result.isSuccess{
let json = JSON(result.value!)
// if response is valid, fill in the varibles with JSON returned data
self._date = currentDateFromUnix(unixDate: json["currently"]["time"].double)
self._currentTemp = json["currently"]["temperature"].double
self._feelsLike = json["currently"]["apparentTemperature"].double
completion(true)
} else {
completion(false)
print("No Result found for this location")
}
}
}
}
Should this json respone be stored somewhere? Is there a way to pass it between (model)classes without starting a new request?