我一直在从事一个个人项目,并在 swift 4 中为 iOS 制作了一个天气检查应用程序,我让 OpenWeatherMap API 工作并解析 JSON 数据,我可以在控制台中获取它们的值。现在我想简单地将标签“T”的值设置为等于“ggtemp”的值,即当前温度。 我尝试将其放在 if 语句中,
if T != nil
执行此操作等,但我无法让任何东西发挥作用。如有帮助,我们将不胜感激。
代码如下:
import UIKit
struct Coordinate : Decodable {
let lat, lon : Double?
}
struct Weather : Decodable {
let id : Int?
let main, description, icon : String?
}
struct Sys : Decodable {
let type, id : Int?
let sunrise, sunset : Date?
let message : Double?
let country : String?
}
struct Main : Decodable {
let temp, tempMin, tempMax : Double?
let pressure, humidity : Int?
}
struct Wind : Decodable {
let speed : Double?
let deg : Int?
}
struct MyWeather : Decodable {
let coord : Coordinate?
let cod, visibility, id : Int?
let name : String?
let base : String?
let weather : [Weather]?
let sys : Sys?
let main : Main?
let wind : Wind?
let dt : Date?
}
class ViewController: UIViewController {
//Labels
@IBOutlet weak var thumidity: UILabel!
@IBOutlet weak var tmain: UILabel!
@IBOutlet weak var ttemp: UILabel!
@IBOutlet weak var tspeed: UILabel!
@IBOutlet weak var gmain: UILabel!
@IBOutlet weak var gtemp: UILabel!
@IBOutlet weak var ghumidity: UILabel!
@IBOutlet weak var gspeed: UILabel!
@IBOutlet weak var T: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=Crowland&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric") else { return }
URLSession.shared.dataTask(with: APIUrl) { data, response, error in
guard let data = data else { return }
let decoder = JSONDecoder()
do {
let weatherData = try decoder.decode(MyWeather.self, from: data)
if let gmain = weatherData.weather?.description {
print(gmain)
// tmain.text = String(describing: gmain)
}
if let gspeed = weatherData.wind?.speed {
print(gspeed)
//speed.text = String(gspeed)
}
if let ghumidity = weatherData.main?.humidity {
print(ghumidity)
}
if let ggtemp = weatherData.main?.temp {
print(ggtemp, "TEST")
self.T.text? = String (ggtemp)
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
}
如果你写 self.T.text 时不带问号(这意味着它是可选的或者可以是 nil)怎么办?
您的标签可能未在界面生成器中注册。从情节提要中检查该视图上的插座并确保它在那里 - 因为文本的值是可选的,但标签本身不是(强制包裹)(!)
在调用该标签值时设置断点,并检查该标签本身是否不为零