새소식

개발일지

TripMate (1) - openweatherAPI와 CLLocationManager 사용하기

  • -

 

새로 시작하는 프로젝트에서 날씨를 가져오는 API를 사용하게 되었다.

예전 패스트캠퍼스 강의에서 날씨 앱을 만들 때 사용했던 openweather API를 사용했다.

 

 

С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

 

 

5 Day / 3 Hour Forecast

 

링크를 접속하면 다양한 조건으로 날씨를 가져올 수 있다. 그중 나는 5 Day / 3 Hour Forecast를 사용하였다.

API 문서를 보면 필수적으로 호출 해야하는 파라미터 중 lat(위도), lon(경도), app Key가 있다.

api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={API key}

 

 

CLLocationManager로 현재 위치의 위도(latitude)와 경도(longitude)를 가져왔다.

API에서 추가적으로 도시 이름을 넣어서 날씨를 받아 올 수도 있다.

private let locationManager: CLLocationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    
}

extension MainViewController: CLLocationManagerDelegate{
	func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        
        let latitude = location.coordinate.latitude		// 위도
        let longitude = location.coordinate.longitude	// 경도
        
         if let country = placemarks?.first?.country {	// 나라
                if let city = placemarks?.first?.locality{ // 도시
            }
        }
    }
}

 

아래는 내가 사용하려고 만든 구조체이다.

struct WeatherInfomation: Codable{
    let cod: String
    let weather: [Weather]
    
    enum CodingKeys: String, CodingKey{
        case cod
        case weather = "list"
    }
}

struct Weather: Codable{
    let temperature: WeatherTemperature
    let weatherDetail: [WeatherDetail] // 날씨
    let pop: Double // 강수 확률
    let date: Date? // 시간
    
    enum CodingKeys: String, CodingKey{
        case temperature = "main"
        case weatherDetail = "weather"
        case pop
        case date = "dt_txt"
    }
}

struct WeatherTemperature: Codable{
    let temp: Double		// 현재 기온
    let temp_min: Double	// 최저 기온
    let temp_max: Double	// 최고 기온
}

struct WeatherDetail: Codable{
    let main: String // 현재 날씨(맑음, 구름 등등)
    let icon: String // 날씨 아이콘
}

 


WeatherDetail
에서 icon을 사용하여 현재 날씨의 이미지(구름, 해 등)를 불러올 수도 있다.

"https://openweathermap.org/img/wn/\(icon)@2x.png"

 

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.