简体   繁体   English

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

[英]Sharing data between URLSession.shared.dataTask and ViewController

I am having problem sharing data between URLSession.shared.dataTask and the ViewController class. 我在URLSession.shared.dataTaskViewController类之间共享数据时遇到问题。 I am using a DispatchQueue and seems to work well when storing directly to label , however, when I try to store information to local fields this approach is not working. 我正在使用DispatchQueue ,并且在直接存储到label时似乎工作良好,但是,当我尝试将信息存储到本地字段时,这种方法不起作用。

This is my current code: 这是我当前的代码:

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

The plantManager field is nil and obviously, I can't access the is getter plantManager.getExtTemp() . plantManager字段为nil ,显然,我无法访问getter plantManager.getExtTemp() I am new using Swift and I can't understand why this approach works to write to labels but does not when using fields. 我是使用Swift的新手,我不明白为什么这种方法可以写标签,但是在使用字段时却不能。

Really appreciate a hand. 真的很感激一只手。 Thank you in advance. 先感谢您。

dataTask works asynchronously, use a completion handler: dataTask异步工作,请使用完成处理程序:

Declare the method 声明方法

func getPlantData(completion: ()->()) {

and replace 并更换

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

with

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

and call it in viewDidLoad 并在viewDidLoad调用它

getPlantData() { 
    print("Info To Print:" + plantManager.getExtTemp())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在URLSession.shared.dataTask期间从异步关闭存储数据 - Storing data from an asynchronous closure during URLSession.shared.dataTask URLSession.shared.dataTask接收数据的正确方法 - URLSession.shared.dataTask correct way to receive data 在URLSession.shared.dataTask之后调用performSegue - Call performSegue after URLSession.shared.dataTask URLSession.shared.dataTask 冻结 UI - URLSession.shared.dataTask freezes the UI 在URLSession.shared.dataTask中执行performSegueWithIdentifier(with:url) - performSegueWithIdentifier while in URLSession.shared.dataTask(with: url) iOS:来自 URLSession.shared.dataTask 的数据(带有:url 始终为零(在 xcode 调试器中显示 0 字节错误?) - iOS: Data from URLSession.shared.dataTask(with: url is always nil (display 0 bytes bug in xcode debugger?) 命中Node Express端点时URLSession.shared.dataTask数据始终为空 - URLSession.shared.dataTask Data is Always Empty When Hitting Node Express Endpoint 如何获取请求中标头的值(URLSession.shared.dataTask(with:request){(数据,响应,错误) - How get value of headers in request (URLSession.shared.dataTask(with: request) { (data, response, error) 当应用程序处于后台时调用URLSession.shared.dataTask - Invoke URLSession.shared.dataTask when the app is background URLSession.shared.dataTask的完成处理程序内部的闭包 - closure inside completion handler of URLSession.shared.dataTask
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM