1
我在我的函數中做了一個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()
}
}
您在塊完成後訪問變量嗎?喜歡它的韭菜將運行異步。 – Eiko
我認爲你必須使用self.temperatureF。 – ryantxr
順便說一句,你不應該使用xcode標籤,因爲你不會問關於xcode的問題。謝謝。 – ryantxr