開始來把資料呈現到畫面上囉~
Step1. 先在畫面拉出數個Label,如下圖
Step2. 接著將每個Label做連結
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var feltairtempLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var rainfallLabel: UILabel!
@IBOutlet weak var sunriseLabel: UILabel!
@IBOutlet weak var sunsetLabel: UILabel!
Step3. 客製化decode後的數值
struct DataResponse: Decodable {
let desc: String
let temperature: Int
let felt_air_temp: Int
let humidity: Int
let rainfall: Int
let sunrise: String
let sunset: String
}
Step4. 解析JSON資料,並放入Label
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://works.ioa.tw/weather/api/weathers/112.json")
//解析JSON
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let _ = data, error == nil else { return }
do{
let LabelValues = try JSONDecoder().decode(DataResponse.self, from: data!)
DispatchQueue.main.async {
//描述
self.descLabel.text = "\(LabelValues.desc)"
//溫度
self.temperatureLabel.text = "\(LabelValues.temperature)"
//體感溫度
self.feltairtempLabel.text = "\(LabelValues.felt_air_temp)"
//濕度
self.humidityLabel.text = "\(LabelValues.humidity)"
//雨量
self.rainfallLabel.text = "\(LabelValues.rainfall)"
//日出時間
self.sunriseLabel.text = "\(LabelValues.sunrise)"
//日落時間
self.sunsetLabel.text = "\(LabelValues.sunset)"
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
Step5. 完成後畫面
完整代碼:
import UIKit
struct DataResponse: Decodable {
let desc: String
let temperature: Int
let felt_air_temp: Int
let humidity: Int
let rainfall: Int
let sunrise: String
let sunset: String
}
class ViewController: UIViewController {
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var feltairtempLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var rainfallLabel: UILabel!
@IBOutlet weak var sunriseLabel: UILabel!
@IBOutlet weak var sunsetLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://works.ioa.tw/weather/api/weathers/112.json")
//解析JSON
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let _ = data, error == nil else { return }
do{
let LabelValues = try JSONDecoder().decode(DataResponse.self, from: data!)
DispatchQueue.main.async {
//描述
self.descLabel.text = "\(LabelValues.desc)"
//溫度
self.temperatureLabel.text = "\(LabelValues.temperature)"
//體感溫度
self.feltairtempLabel.text = "\(LabelValues.felt_air_temp)"
//濕度
self.humidityLabel.text = "\(LabelValues.humidity)"
//雨量
self.rainfallLabel.text = "\(LabelValues.rainfall)"
//日出時間
self.sunriseLabel.text = "\(LabelValues.sunrise)"
//日落時間
self.sunsetLabel.text = "\(LabelValues.sunset)"
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
}