0

URLSession.shared.dataTaskViewController班级之间共享数据时遇到问题。我正在使用 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 的新手,我不明白为什么这种方法可以写入标签,但在使用字段时却不行。

真的很感谢一手。先感谢您。

4

1 回答 1

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())
}
于 2017-05-18T14:56:44.650 回答