ios 无法解析来自API请求Swift的数据

ua4mk5z4  于 2023-01-18  发布在  iOS
关注(0)|答案(1)|浏览(160)

我目前正在学习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&current_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()
    }
}
nhaq1z21

nhaq1z211#

第一件事,网址是空白的,你应该这样更新它。

static let url = URL(string: "https://api.open-meteo.com/v1/forecast?latitude=42.70&longitude=23.32&current_weather=true")

此外,您需要更新Weather结构中的currentweather属性。响应中的名称约定不同。因此,您可以使用此结构来代替。另一方面,您可以检查CodingKeys以获得更好的属性名称。

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 current_weather: currentWeather
}

相关问题