I am having problem sharing data between URLSession.shared.dataTask
and the ViewController
class. 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.
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())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.