我目前正在学习Swift,我尝试从一个使用Codable的开放API中解析数据。我遵循了一些教程,并以非数据获取结束。
可编码:
import Foundation
struct currentWeather: Codable {
var temperature: Double
var time: String
var weathercode: Double
var winddirection: Double
var windspeed: Double
}
struct Weather: Codable {
var elevation: Double
var latitude: Double
var longitude: Double
var timezone: String
var timezone_abbreviation: String
var utc_offset_seconds: Int
var generationtime_ms: Double
var currentweather: currentWeather
}
请求管理器:
import Foundation
class RequestManager {
static let url = URL(string: "https://api.open-meteo.com/v1/forecast? latitude=42.70&longitude=23.32¤t_weather=true")
static var temperature: Double = 0.0
class func getWeatherData() {
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request, completionHandler: {
(data, response, error) in
guard let weather = try? JSONDecoder().decode(Weather.self, from: data!) else {
print("Cannot parse data!")
return
}
RequestManager.temperature = weather.currentweather.temperature
})
task.resume()
}
}
1条答案
按热度按时间nhaq1z211#
第一件事,网址是空白的,你应该这样更新它。
此外,您需要更新Weather结构中的currentweather属性。响应中的名称约定不同。因此,您可以使用此结构来代替。另一方面,您可以检查CodingKeys以获得更好的属性名称。