我URLSession.shared.dataTask
在ViewController
班级之间共享数据时遇到问题。我正在使用 a并且在直接存储到labelDispatchQueue
时似乎运行良好,但是,当我尝试将信息存储到本地字段时时,这种方法不起作用。
这是我当前的代码:
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()
}
}
该plantManager
字段nil
显然是,我无法访问 is getterplantManager.getExtTemp()
。我是使用 Swift 的新手,我不明白为什么这种方法可以写入标签,但在使用字段时却不行。
真的很感谢一手。先感谢您。