在URLSession.shared.dataTask和ViewController之间共享数据

时间:2017-05-18 14:44:48

标签: ios swift urlsession

我遇到了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 getter plantManager.getExtTemp()。我是使用Swift的新手,我无法理解为什么这种方法可以写入标签,但在使用字段时则不行。

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

1 个答案:

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