Devlog👩🏻💻/iOS
[iOS] CoreLocation 사용하기
yujjne
2025. 2. 14. 01:00
CoreLocation을 사용해서 현재 위치 데이터를 받아와보자 📍
1. CoreLocation 설정 (현재 위치 받아오기)
CoreLocation 프레임워크를 사용해서 사용자의 위치 정보를 가져올 수 있다.
✅ Info.plist 설정
위치 권한 요청을 위한 키를 추가해야 한다.
<key>NSLocationWhenInUseUsageDescription</key>
<string>앱 사용 중 현재 위치를 확인하기 위해 필요합니다.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>항상 현재 위치를 확인하기 위해 필요합니다.</string>
2. LocationManager 클래스 생성
위치 정보를 관리하는 클래스를 만들어 현재 위치를 불러오기.
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
@Published var currentLocation: CLLocation?
@Published var authorizationStatus: CLAuthorizationStatus?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest // 정확도 설정
requestLocationPermission()
}
func requestLocationPermission() {
locationManager.requestWhenInUseAuthorization() // 앱 사용 중 위치 권한 요청
locationManager.startUpdatingLocation() // 위치 업데이트 시작
}
}
extension LocationManager: CLLocationManagerDelegate {
// 위치 권한 상태 변경 시 호출
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.authorizationStatus = status
switch status {
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation()
case .denied, .restricted:
print("위치 권한이 거부되었습니다.")
default:
break
}
}
// 위치 업데이트 시 호출
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
self.currentLocation = location
locationManager.stopUpdatingLocation() // 한 번 받아오면 업데이트 중단
}
// 위치 업데이트 실패 시 호출
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("위치 업데이트 실패: \(error.localizedDescription)")
}
}
📌 현재 위치를 불러오는 과정 정리
✅ currentLocation이 업데이트되는 과정
1️⃣ 앱 실행 → LocationManager 초기화 (init())
- locationManager.delegate = self → CLLocationManagerDelegate 설정
- requestLocationPermission() → 위치 권한 요청
2️⃣ 사용자가 위치 권한을 허용하면 (didChangeAuthorization)
- startUpdatingLocation() 실행 → GPS 위치 정보 업데이트 시작
3️⃣ 새로운 위치가 감지되면 (didUpdateLocations)
- currentLocation = location으로 @Published 프로퍼티 업데이트
- ViewController에서 이 값을 구독하고 원하는 동작 ( 아래로 . . )
3. ViewController > currentLocation 구독
// 위치 업데이트 바인딩
private func bindLocationUpdates() {
locationManager.$currentLocation
.compactMap { $0 } // nil 값 필터링
.sink { [weak self] location in
self?.customFunc // 원하는 동작
}
.store(in: &cancellables)
}
- locationManager.$currentLocation은 LocationManager에서 위치가 변경될 때마다 업데이트
- 이를 sink를 통해 구독하여, 새로운 위치가 들어오면 customFunc 호출해서 원하는 동작(UI 업데이트 등 !)
✅ authorizationStatus 구독 (필요하면 추가 가능)
위치 권한이 변경될 때 UI를 업데이트하고 싶다면 다음처럼 구독할 수 있다.
private func bindAuthorizationStatus() {
locationManager.$authorizationStatus
.sink { status in
switch status {
case .authorizedWhenInUse, .authorizedAlways:
print("위치 권한 허용됨")
case .denied, .restricted:
print("위치 권한 거부됨")
default:
break
}
}
.store(in: &cancellables)
}
1. locationManager.requestWhenInUseAuthorization()을 호출하면 didChangeAuthorization이 실행
2. authorizationStatus 값이 변경
3. 이를 구독하는 곳(bindAuthorizationStatus())에서 변경된 권한 상태에 따라 UI를 업데이트할 수 있음
설정 후 앱을 실행하면 위치 권한 요청 팝업이 표시된다.
권한을 허용하면 현재 위치를 불러온다 !
참고로 시뮬레이터에서 테스트할 때는 위치 설정을 시뮬레이터 메뉴에서 조정할 수 있다.
- Feature > Location > Custom Location
- 실제 디바이스에서는 위치 서비스 설정 on
이렇게 하면 현재 위치를 불러오기가 가능하다.
✅ 최종 흐름
🔹위치 권한 요청 → GPS에서 현재 위치 가져오기 → currentLocation 업데이트 → ViewController(customFunc) 🚀