前面幾天已經練習了如何呈現 JSON 資料在 App 上,在最後完賽前會做一個天氣 App 出來,而 JSON 的資料由中央氣象局提供。
struct Weather: Codable {
var records: records
}
struct records: Codable {
var location: [location]
}
struct location: Codable {
var locationName: String
var weatherElement: [weatherElement]
}
struct weatherElement: Codable {
var elementName: String
var time: [time]
}
struct time: Codable {
var startTime: String
var endTime: String
var parameter: parameter
}
struct parameter: Codable {
var parameterName: String
var parameterValue: String?
var parameterUnit: String?
// 注意 parameterValue 和 parameterUnit 不一定存在,所以宣告成 String?
}
import UIKit
class ViewController: UIViewController {
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)
}
else {
print("error")
}
}
task.resume()
}
}
執行看看,確認寫好的 struct 沒有問題。