昨天已經把 struct 寫好了,今天來呈現資料在手機畫面上,在此之前可以先上網搜尋 API 說明文件,方便自己刻 UI。
elementName 所代表的意義如下。
Wx. 天氣現象. MaxT. 最高溫度. MinT. 最低溫度. CI. 舒適度. PoP. 降雨機率.
幫 Label 連接好 IBOutlet。
改寫先前的程式,讓 Label 呈現出資料。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var locationName: UILabel!
@IBOutlet weak var Wx: UILabel!
@IBOutlet weak var PoP: UILabel!
@IBOutlet weak var MinT: UILabel!
@IBOutlet weak var CI: UILabel!
@IBOutlet weak var MaxT: UILabel!
@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var endTime: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=CWB-6F803E34-66E5-4135-AC7D-25811AD53D5C&format=JSON&locationName=%E5%AE%9C%E8%98%AD%E7%B8%A3")!,timeoutInterval: Double.infinity)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request){(data, respond, error) in
let decoder = JSONDecoder()
if let data = data, let weather = try? decoder.decode(Weather.self, from: data){
print(weather)
DispatchQueue.main.sync {
self.locationName.text = weather.records.location[0].locationName
self.Wx.text = weather.records.location[0].weatherElement[0].time[0].parameter.parameterName
self.PoP.text = weather.records.location[0].weatherElement[1].time[0].parameter.parameterName + "%"
self.MinT.text = weather.records.location[0].weatherElement[2].time[0].parameter.parameterName + "°" + weather.records.location[0].weatherElement[2].time[0].parameter.parameterUnit!
self.CI.text = weather.records.location[0].weatherElement[3].time[0].parameter.parameterName
self.MaxT.text = weather.records.location[0].weatherElement[4].time[0].parameter.parameterName + "°" + weather.records.location[0].weatherElement[4].time[0].parameter.parameterUnit!
self.startTime.text = weather.records.location[0].weatherElement[0].time[0].startTime
self.endTime.text = weather.records.location[0].weatherElement[0].time[0].endTime
}
}
else {
print("error")
}
}
task.resume()
}
}
執行看看。