비전공자 개발일기

Weather Information 본문

SWIFT

Weather Information

HiroDaegu 2022. 12. 16. 23:08
728x90
SMALL

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 

Open API를 활용한 날씨 조회

import Foundation

struct ErrorMsg: Codable {
    let message: String
}
import Foundation

struct WeatherInformation: Codable {
    let weather: [Weather]
    let temp: Temp
    let name: String
    
    enum CodingKeys: String, CodingKey {
    case weather
    case temp = "main"
    case name
    }
}

struct Weather: Codable {
    let id: Int
    let main: String
    let description: String
    let icon: String
}

struct Temp: Codable {
    let temp: Double
    let feelsLike: Double
    let minTemp: Double
    let maxTemp: Double
    
    enum CodingKeys: String, CodingKey {
    case temp
    case feelsLike = "feels_like"
    case minTemp = "temp_min"
    case maxTemp = "temp_max"
    }
}
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var cityNameTextField: UITextField!
    @IBOutlet weak var cityNameLabel: UILabel!
    @IBOutlet weak var weatherDescriptionLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!
    @IBOutlet weak var maxTempLabel: UILabel!
    @IBOutlet weak var minTempLabel: UILabel!
    @IBOutlet weak var weatherStackView: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    @IBAction func searchWeatherBTN(_ sender: UIButton) {
        if let cityName = cityNameTextField.text {
            getCurrentWeahter(cityName: cityName)
            view.endEditing(true)
        }
    }
    
    func configureView(weatherInformation: WeatherInformation) {
        cityNameLabel.text = weatherInformation.name
        if let weahter = weatherInformation.weather.first {
            weatherDescriptionLabel.text = weahter.description
        }
        tempLabel.text = "\(Int(weatherInformation.temp.temp - 273.15))°C"
        maxTempLabel.text = "MAX: \(Int(weatherInformation.temp.maxTemp - 273.15))°C"
        minTempLabel.text = "MIN: \(Int(weatherInformation.temp.minTemp - 273.15))°C"
    }
    
    func showAlert(msg: String) {
        let alert = UIAlertController(title: "Error", message: msg, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    func getCurrentWeahter(cityName: String) {
        guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}") else { return }
        let session = URLSession(configuration: .default)
        session.dataTask(with: url) { [weak self] data, response, error in
            let successRange = (200..<300)
            guard let data = data, error == nil else { return }
            let decoder = JSONDecoder()
            if let response = response as? HTTPURLResponse, successRange.contains(response.statusCode) {
                guard let weatherInformation = try? decoder.decode(WeatherInformation.self, from: data) else { return }
                DispatchQueue.main.async {
                    self?.weatherStackView.isHidden = false
                    self?.configureView(weatherInformation: weatherInformation)
                }
            } else {
                guard let errorMsg = try? decoder.decode(ErrorMsg.self, from: data) else { return }
                DispatchQueue.main.async {
                    self?.showAlert(msg: errorMsg.message)
                }
            }
        }.resume()
    }
}
728x90
LIST

'SWIFT' 카테고리의 다른 글

Status of COVID-19 outbreak(CocoaPods, Alamfire, Charts)  (0) 2022.12.17
Do not Work pod init in workspace  (0) 2022.12.17
Pomodoro Timer  (0) 2022.12.15
To Do List  (0) 2022.12.14
Basic Calculator  (0) 2022.12.13