上次我們解包完資料,接下來要使用資料
CallAPI(finish: @escaping (() -> Void)) 函式是用於呼叫 API 來取得天氣資料。
函式內容如下:
func CallAPI(finish: @escaping (() -> Void)) {
// print(String(describing: CodingString!))
let address = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=CWB-C1F1124A-2966-4D8B-9E96-BCDECED47A0E&locationName=\(String(describing: CodingString!))"
// print(address)
let url = URL(string: address)
URLSession.shared.dataTask(with: url!) { [self] data, response, error in
if let error = error {
print(error.localizedDescription)
}
if let response = response {
print(response as! HTTPURLResponse)
}
if let data = data {
let decoder = JSONDecoder()
do {
let WeatherData = try decoder.decode(WeatherResponse.self, from: data)
print("==============================================================================")
print(WeatherData)
downloadData = WeatherData
print(downloadData?.records.location[0].weatherElement[0].time[0].endTime ?? "")
print("==============================================================================")
} catch {
print(error.localizedDescription)
}
finish()
}
}.resume()
// tableView.reloadData()
}