我在URLSession.shared.dataTaskViewController类之间共享数据时遇到问题。我使用的是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 getterplantManager.getExtTemp()。我是使用Swift的新手,我不明白为什么这种方法对标签起作用,但在使用字段时却不起作用。
非常感谢你的帮助。提前谢谢你。

最佳答案

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

关于ios - 在URLSession.shared.dataTask和ViewController之间共享数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44050959/

10-11 00:34