iOS/iOS SeSAC 2기 TIL

[iOS swift] 과제) 날씨 API 통신 및 label에 표시

Developer-Michelle 2022. 8. 15. 14:54

과제) 날씨 API 통신 및 label에 표시

 

https://openweathermap.org/weather-conditions

 

Weather Conditions - OpenWeatherMap

Weather Conditions Home Weather Conditions

openweathermap.org

위의 API이용

 

파일 3개로 구성 + 이외 스토리보드1개 이용

1) WeatherModel.swift 

2) WeatherAPIManager.swift

3) WeatherViewController.swift

 

1) WeatherModel.swift 

 

2) WeatherAPIManager.swift

코드 부분 하나씩 뜯어서 생각해보기

 

typealias completionHandler = (WeatherModel, String) -> Void

    

    func callRequest(lat: Double, lon: Double, completionHandler: @escaping completionHandler) {

        let url = "https://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)&appid=\(APIKey.weather)"

 

- WeatherViewController 파일에서 latitude, longitude (현재 위도 경도를 받아오는 부분이 있는데, 이 값을 넣어주어야 url을 이용할 수 있으므로 일단 callRequest함수의 초입부분에서 lat, lon 을 double타입으로서 매개변수처럼 넣어줌)

 

- typealias completionHanlder부분에서 결국 WeatherViewController에 전달해주어야하는 데이터인 weatherData, iconImage의 타입 선언을 해줌 (WeatherModel(구조체 형태), String 타입으루)

참고로, weatherData, iconImage 은 해당 WeatherAPIManager파일의 맨 마지막에서 결국 만들어지는 최종 데이터임. 이 데이터를 WeatherViewController에 전달해주는 것임.

 

 

해당파일(APIManager)의 마지막 부분에서 아래와 같이 weatherData에 API통신 한 값들을 모두 넣어줌.

이로써, WeatherModel구조체 파일의 값을 weatherData에 담은 거고, 

 

let weatherData: WeatherModel = WeatherModel(time: time, location: location, temperature: temperature, humidity: humidity, wind: wind, latitude: lat, longitude: lon)

                

completionHandler(weatherData, iconImage)

 

위의 weatherData는 WeatherViewController에서 var weatherData: WeatherModel! 로 선언함으로써 이용된다.

 

 

 

3) WeatherViewController.swift

 

현재 위치를 위도, 경도로 가져온 부분. (새로고침 버튼 클릭시 print)

여기에서 위도 경도 값을 받아와서 아래처럼 APIManager에서 callRequest 함수 만들었던 부분을 불러오는 것.

(lat, lon 값이 있어야 서버 통신을 시작할 수 있으므로 위도, 경도 값을 얻는 부분부터 시작)

 

WeatherAPIManager.shared.callRequest(lat: latitude ?? 0, lon: longitude ?? 0) { weather, image in

            self.weatherData = weather

            

            self.temperatureLabel.text = "지금은 \(self.weatherData.temperature - 273.15)도 입니다."

 

이 때, APIManager에서 weatherData, iconImage 를 weather,image로 받아와 밑에 라벨에 다 뿌려주는 거.

 

위의 파일을 살펴보다보면 왜 APIManager에서 아래와 같이 선언했었는지 알게 됨(반환 값이 없는 형태로 그저 weatherData와 iconImage만 전달받았을 뿐임)

typealias completionHandler = (WeatherModel, String) -> Void

 

 

 

결국 정리하자면,

APIManager에서 값을 받아와서 WeatherVC에 뿌려주는 꼴.

 

 

전체코드는 아래에

https://github.com/SeungYeonMichelleYoo/SeSACWeek6

 

GitHub - SeungYeonMichelleYoo/SeSACWeek6

Contribute to SeungYeonMichelleYoo/SeSACWeek6 development by creating an account on GitHub.

github.com