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을 사용하여 현재 날씨의 이미지(구름, 해 등)를 불러올 수도 있다.