
// ViewController
import CoreLocation
extension ViewController: CLLocationManagerDelegate {
private func configureLocation() {
manager.delegate = self
validateIsTurnedOnSystemAuthorization()
}
private func validateIsTurnedOnSystemAuthorization() {
if CLLocationManager.locationServicesEnabled() {
// 위치 서비스가 활성화 되어 있다면 이 분기로 빠진다.
getUserLocationAuth()
} else {
print("유저가 시스템상 위치 서비스를 활성화 해야 합니다.")
}
}
}private func getUserLocationAuth() {
switch manager.authorizationStatus {
case .notDetermined:
// 여기서 위치 정보 획득 권한을 얻는 alert를 띄워준다.
// 반드시 info.plist에서 설정한 권한 형식으로 간다.
manager.requestWhenInUseAuthorization()
case .denied:
print("권한을 확보해야 함")
case .authorizedWhenInUse:
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
default: print("")
}
}func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
validateIsTurnedOnSystemAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locate = locations.last?.coordinate else { return }
AF.request(url).responseDecodable(of: WeatherModel.self) { res in
switch res.result {
case .success(let v):
// API 통신 성공에 따른 비즈니스 로직이 온다.
// 현재 위치를 한 번만 사용하는 앱이라면 위치 정보 업데이트를 멈출 수도 있다.
self.manager.stopUpdatingLocation()
case .failure(let e):
print(e)
}
}
}