Home > Software design >  Unable to parse data from API Request Swift
Unable to parse data from API Request Swift

Time:01-17

I am currently working on learning Swift and I tried to parse data from an open API working with Codable. I followed some tutorials and ended with non data fetched.

Codable:

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
}

RequestManager:

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()
    }
}

CodePudding user response:

First things first, url has blanks, you should update it like that.

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

Further, you need to update currentweather property in the Weather struct. The name convention is different in the response. So you can use this struct instead. On the other hand, you may check CodingKeys for better property names.

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
}
  • Related