тыц

← разместить еще код

Расшаренный код:

import Foundation 

struct WeatherParametersModel: Codable {

    struct Coord:Codable
    {
       let lon: Double // City geo location, longitude
       let loc: Double // City geo location, latitude
    }

    let coord: Coord

    struct Weather: Codable // (more info Weather condition codes)
    {
       let  id: Int //Weather condition id
       let  main: String //Group of weather parameters (Rain, Snow, Extreme etc.)
       let  description: String //Weather condition within the group
       let  icon: String //Weather icon id
    }

    let weather: [Weather]

    //let base: String //Internal parameter
    enum TemperatureUnit: String
    {
        case Default
        case Metric
        case Imperial

    }

    struct Main: Codable 
    {
       let temp: Double //Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
       let pressure: Double //Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa
       let humidity: Double //Humidity, %
       let temp_min: Double // Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
       let temp_max: Double // Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
       let sea_level: Double //Atmospheric pressure on the sea level, hPa
       let grnd_level: Double //Atmospheric pressure on the ground level, hPa
    }

    let main: Main

    struct Wind: Codable
    {
      let  speed: Double// Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.
      let deg: Double // Wind direction, degrees (meteorological)
    }

    let wind: Wind

    struct Clouds:Codable
    {
       let  all:Double // Cloudiness, %
    }

    let clouds: Clouds

    struct Rain:Codable
    {
        let  h1: Double // Rain volume for the last 1 hour, mm
        let h3: Double // Rain volume for the last 3 hours, mm
    }

    let rain: Rain

    struct Snow:Codable
    {
        let h1: Double // Snow volume for the last 1 hour, mm
        let h3: Double // Snow volume for the last 3 hours, mm
    }

    let snow: Snow

    let dt:Double // Time of data calculation, unix, UTC

    struct Sys: Codable
    {
        let type: Int //Internal parameter
        let id: Int //Internal parameter
        let message: Double // Internal parameter
        let country: String //Country code (GB, JP etc.)
        let sunrise: Double // Sunrise time, unix, UTC
        let sunset: Double // Sunset time, unix, UTC
    }

    let sys: Sys

    let id: Int //City ID
    let name: String // City name
    let cod: Int // Internal parameter
}

func getWeather(_ city: String, _ completion: @escaping ((WeatherParametersModel) -> Void)){

        //let cellcium = "metric"

        let APPID="9d4e0ceff703380b2f9060687786363f"

        let weatherURL = URL(string:"https://api.openweathermap.org/data/2.5/weather?q=\(city)&units=metric&APPID=\(APPID)")!

        let session = URLSession.shared

        let dataTask = session.dataTask(with: weatherURL) //create task
        {
            (data, response, error) in
            if let error = error //check error
            {
                print("Error1:\(error)")
            }
            else
            {
                guard let dataResponse = data,error == nil else {
                        //let dataString = String(data:data,encoding: String.Encoding.utf8)
                        print(error?.localizedDescription ?? "Response Error")
                        return
                }
                do{
                    let decoder = JSONDecoder()
                    let weatherModel = try decoder.decode( WeatherParametersModel.self, from: dataResponse) // decode json in model
                    //print(weatherModel  
                    completion(weatherModel)

                } catch let parsingError
                {
                    print("Error2", parsingError)
                }
            }            
        }
     dataTask.resume()
}
let w = getWeather("kiev",{weatherModel in print(weatherModel)})
print(w)