import CoreLocation
let locationManager = CLLocationManager()
var geocoder = CLGeocoder()
CLLocationManagerDelegate
❖ 사용자 위치가 업데이트되었을 때 위도 경도 구하기 : didUpdateLocations
var geocoder = CLGeocoder()
var afterUpdateLocationUpdateWeatherDataWith: ((String?, String?, Double?, Double?) -> Void)?
func locationManager(_ manager: CLLocationManager, didUpdateLocations **locations**: [CLLocation]) {
guard let location = **locations**.first else { return }
// 최근 위치를 기반으로 도시명, 위도 경도 값을 구한다
geocoder.**reverseGeocodeLocation**(location) { [weak self] **placemarks**, error in
if let error = error {
print("❌ Error while updating location with \\(error.localizedDescription)")
return
}
if let firstLocation = **placemarks**?[0] {
let cityName = firstLocation.locality ?? "-"
let countryName = firstLocation.country ?? "-"
let lon = firstLocation.location?.coordinate.longitude ?? 0
let lat = firstLocation.location?.coordinate.latitude ?? 0
self?.longitude = lon
self?.latitude = lat
// 🙋🏻♂️ 업데이트를 중지하지 않으면 계속 사용자 위치를 업데이트한다
self?.locationManager.stopUpdatingLocation()
// 🙋🏻♂️ 클로져로 데이터 전달
self?.afterUpdateLocationUpdateWeatherDataWith?(cityName, countryName, lon, lat)
}
}
}
🙋🏻♂️ reverseGeocodeLocation에 왜 reverse (역방향)가 들어가지?
- reverse geocoding : 좌표 (위도, 경도) ⇒ 주소
- forward geocoding : 주소 ⇒ 좌표
❖ 사용자 위치 제공 권한이 바뀌었을 때 : locationManagerDidChangeAuthorization
❖ 에러 : didFailWithError
옵셔널 클로져로 데이터 전달