我正在函数中进行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()
}
}
现在可以使用了。我访问变量的方式存在问题。感谢所有的建议。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句