变量未在完成处理程序中设置

时间:2016-04-27 05:50:19

标签: swift api

我正在我的函数中进行api调用,并尝试使用API​​调用中的值来改变类变量temperatureF的值。 API正在通过,我没有收到任何错误消息,但变量没有被更改。我的代码如下。出于安全原因,API的URL已更改。我也尝试将self.temperature行调度到主队列,但这也不起作用。

class weatherModel {

    var temperatureF : Float? = 1

    func readWeather(){

        let postEndpoint: String = "myurl.com"
        guard let weatherUrl = NSURL(string: postEndpoint) else {
            print ("Error: cannot create URL")
            return
        }
        let urlRequest = NSURLRequest(URL: weatherUrl)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)

        let task = session.dataTaskWithRequest(urlRequest) {
            (data: NSData?,  response: NSURLResponse?, error: NSError?) in

            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }

            guard error == nil else {
                print("error calling GET on /posts/1")
                print(error)
                return
            }
            // parse the result as JSON, since that's what the API provides
            let post: NSDictionary
            do {
               post = try NSJSONSerialization.JSONObjectWithData(responseData,
                    options: []) as! NSDictionary
            } catch {
                print("error trying to convert data to JSON")
                return
            }

          self.temperatureF = post["current_observation"]!["temp_f"] as? Float


    }
    task.resume()    
}
}

1 个答案:

答案 0 :(得分:0)

现在有效。这是我访问变量的一个问题。感谢您的所有建议。