Search code examples
iosjsonswift

How can I retrieve data stored in a seperate class when calling from ViewController?


I am currently learning iOS development using Swift. I am making a simple weather app. I have several buttons to get the weather for the next 4 hours. I am getting the weather from the dark sky API, returned in JSON format. I have finally figured out how to retrieve the correct data from the JSON, and have created a class that fetches the data.

typealias WeatherCallback = (Weather) -> Void
typealias ErrorCallback = (Error) -> Void

class NetworkManager {
    
    class func getWeather(latitude: String, longitude: String, onSuccess: WeatherCallback? = nil, onError: ErrorCallback? = nil) {
        
        let urlString = "https://api.darksky.net/forecast/(api key)/" + latitude + "," + longitude + "?units=si"
        
        let url = URL(string: urlString)
        
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print(error!)
                onError?(error!)
            } else {
                do {
                    let json  = JSON(data: data!)
                    let weather = Weather()
                    
                    DispatchQueue.main.async {
                        weather.updateWithJSON(dict: json["currently"], hour: 0)
                        
                        for i in 1...4 {
                            weather.updateWithJSON(dict: json["hourly"]["data"][i], hour: i)
                        }
                    }
                    onSuccess?(weather) 
                }
            }
            }.resume()
    }
}

And I have a different class to store the retrieved data.

class Weather {
   
    public var currentTime: String = ""
    public var currentTemperature: String = ""
    
    public var nextHourTime: String = ""
    public var nextHourTemperature: String = ""
    
    public var nextTwoHourTime: String = ""
    public var nextTwoHourTemperature: String = ""
    
    public var nextThreeHourTime: String = ""
    public var nextThreeHourTemperature: String = ""
    
    public var nextFourHourTime: String = ""
    public var nextFourHourTemperature: String = ""
    
    func updateCurrentData(time: String, temp: String) {
        currentTime = time
        currentTemperature = temp
    }
    
    func updateWithJSON(dict: JSON, hour: Int){
        
        switch hour {
        case 0:
            currentTime = dict["time"].stringValue
            currentTemperature = dict["temperature"].stringValue
            
        case 1:
            nextHourTime = dict["time"].stringValue
            nextHourTemperature = dict["temperature"].stringValue
            
        case 2:
            nextTwoHourTime = dict["time"].stringValue
            nextTwoHourTemperature = dict["temperature"].stringValue
            
        case 3:
            nextThreeHourTime = dict["time"].stringValue
            nextThreeHourTemperature = dict["temperature"].stringValue
            
        case 4:
            nextFourHourTime = dict["time"].stringValue
            nextFourHourTemperature = dict["temperature"].stringValue
            
        default:
            print("rip")
        }
    }
}

My problem is, I cannot access the stored values in the class Weather from within ViewController.

For example

let weather = Weather()

print(weather.currentTime)

Any help in pointing me in the right direction would be awesome!


Solution

  • You can do it by creating Weather class Singleton. Using singleton Only one copy of this object exists and the state is shared and reachable by any other object.

    class Weather {
    public static var sharedInstance =  Weather()
    ...
    private init() {
    }
    }
    

    and get object of singleton like this

    let weather = Weather.sharedInstance // it will give you the same instance of Weather every time you call it.