我遇到了URLSession.shared.dataTask
和ViewController
类之间共享数据的问题。我正在使用DispatchQueue
并且在直接存储到标签时似乎运行良好,但是,当我尝试将信息存储到本地字段时,此方法无法正常工作
这是我目前的代码:
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 getter plantManager.getExtTemp()
。我是使用Swift的新手,我无法理解为什么这种方法可以写入标签,但在使用字段时则不行。
真的很感激一只手。先感谢您。
答案 0 :(得分:1)
dataTask
异步工作,使用完成处理程序:
声明方法
func getPlantData(completion: ()->()) {
并替换
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)!)
})
与
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()
}
并在viewDidLoad
getPlantData() {
print("Info To Print:" + plantManager.getExtTemp())
}