出于某种原因,每当我尝试使用 DispatchQueue
代码块内的 self.infoLabel.text = String(temp!)
更新当前温度的标签时,我收到以下 fatal error 消息:
unexpectedly found nil while unwrapping an Optional value.
如果有人能帮助我找出下面的代码不起作用的原因,我将不胜感激。谢谢。
func getCurrentTemp(city: String){
let weatherRequestURL = URL(string: "\(openWeatherMapBaseURL)?APPID=\(openWeatherMapAPIKey)&q=\(city)")!
// The data task retrieves the data.
URLSession.shared.dataTask(with: weatherRequestURL) { (data, response, error) in
if let error = error {
// Case 1: Error
print("Error:\n\(error)")
}
else {
//print("Raw data:\n\(data!)\n")
//let dataString = String(data: data!, encoding: String.Encoding.utf8)
//print("Human-readable data:\n\(dataString!)")
do {
// Try to convert that data into a Swift dictionary
let weather = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
if let main = weather["main"] as? [String: Any] {
let temp = main["temp"] as? Double
print("temp\(temp!)")
DispatchQueue.main.sync(execute: {
self.infoLabel.text = String(temp!)
})
//return temp as? String
//let temp_max = main["temp_max"] as? Double
//print("temp\(temp_max!)")
//let temp_min = main["temp_min"] as? Double
//print("temp\(temp_min!)")
}
}
catch let jsonError as NSError {
// An error occurred while trying to convert the data into a Swift dictionary.
print("JSON error description: \(jsonError.description)")
}
}
}
.resume()
}
最佳答案
这里有两种可能性:1)要么 temp 为零(它不应该是因为你已经在上面的 print 语句中强制解开它)2)或 infoLabel 为零,如果你断开了 socket 连接,就会发生这种情况。
很容易检查;在您的作业上方创建一个断点,然后在调试控制台中您可以键入:
po self.infoLabel
看看它是否为零。为了更好地测量,您还可以检查温度。
您还可以添加打印语句来检查 self.infoLabel 或断言。
关于swift - 如何使用函数内部的 JSON 数据更新 Swift 3 中的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536866/