I am having problem sharing data between URLSession.shared.dataTaskand the ViewControllerclass. I am using a DispatchQueue and seems to work well when storing directly to label, however, when I try to store information to local fields this approach is not working.
This is my current code:
class ViewController: UITableViewController {
var plantManager: PlantManager!
override func viewDidLoad() {
super.viewDidLoad()
getPlantData()
print("Info To Print:" + plantManager.getExtTemp())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getPlantData(){
let session = URLSession.shared
let urlPath = PlantURL().getFullURL()
let url = NSURL(string: urlPath)!
print(url)
let request = NSURLRequest(url: url as URL)
let dataTask = session.dataTask(with: request as URLRequest) { (data:Data?, response:URLResponse?, error:Error?) -> Void in do{
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]],
let dict = jsonResult.first {
DispatchQueue.main.sync(execute: {
self.plantManager = PlantManager(intTemp: (dict["ExternalTemperature"] as? String)!, moist: (dict["SoilMoisture"] as? String)!, humidity: (dict["AmbientHumidity"] as? String)!, extTemp: (dict["ExternalTemperature"] as? String)!)
})
}else{
print("No Parsing Correctly")
}
}catch let error as NSError{
print(error.localizedDescription)
}
print("done, error: \(error)")
}
dataTask.resume()
}
}
The plantManager field is nil and obviously, I can't access the is getter plantManager.getExtTemp(). I am new using Swift and I can't understand why this approach works to write to labels but does not when using fields.
Really appreciate a hand. Thank you in advance.