变量未在完成处理程序中设置(Variable not being set in completion handler)
我正在函数中调用一个api调用,并试图用API调用的值改变类变量temperatureF的值。 该API正在通过,我没有收到任何错误消息,但该变量没有被更改。 我的代码如下。 由于安全原因,API的网址已被更改。 我也尝试调度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() } }I'm making an api call in my function and trying to mutate the value of the class variable temperatureF with the value from the API call. The API is going through and I'm not getting any error messages, but the variable isn't being changed. My code is below. The url of the API has been changed for security reasons. I also tried dispatching the self.temperature line to the main queue but that didn't work either.
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() } }最满意答案
它现在有效。 这是我访问变量的一个问题。 感谢所有的建议。
It works now. It was a problem with how I was accessing the variable. Thanks for all the suggestions.
更多推荐
发布评论