0

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.

1 Answer 1

1

dataTask works asynchronously, use a completion handler:

Declare the method

func getPlantData(completion: ()->()) {

and replace

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)!)
})

with

DispatchQueue.main.async {
   self.plantManager = PlantManager(intTemp: dict["ExternalTemperature"] as! String, moist: dict["SoilMoisture"] as! String, humidity: dict["AmbientHumidity"] as! String, extTemp: dict["ExternalTemperature"] as! String)
   completion()
}

and call it in viewDidLoad

getPlantData() { 
    print("Info To Print:" + plantManager.getExtTemp())
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your prompt response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.