locationManager를 이용해서 위치 정보 얻는 방법
나중에 또 까먹을 저를 위해 기록하는 거여서 설명이 자세하지 않을 수 있습니다.
여기 아래 유튜브를 보시면 더 자세한 내용을 알 수 있습니다.
출처 - 유튜브 주소
https://www.youtube.com/watch?v=kWAWmWZV0n4
순서는 크게 아래와 같습니다.
- CLLocationManger 인스턴스 생성후 필요한 설정
- Info.plist 에서 필요한 설정
- View에서 location 값 접근
- class를 만들어 CLLocationManger를 가져오고 필요한 설정하기
- 클래스에 NSObject, ObservableObject 설정
- 변수 location은 아직 값을 모르기때문에 nil로 설정, 이후 값을 받아와 할당하게 되면 view에 알릴 수 있도록 @Published로 붙여줌.
- init{ } 오버라이드하여 필요한 설정을 해준다.
- LocationManger 클래스를 extention 하여 필요한 작업을 더 추가해줌.
import Foundation
import CoreLocation
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
@Published var location:CLLocation? = nil
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
}
// 계속 변하는 위치의 값, 변하는 위치의 값을 저장
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.location = location
print(location)
}
}
2. info.plist에서 필요한 설정 (key , value)
Privacy - Location When In Use Usage Description → 선택 후 value 설정
3. View에서 location 값 접근
- @ObservedObject 를 써서 LocationManager Class를 인스턴스 생성하여 준다.
- location이 비어있지 않다면 location 안에 있는 좌표 정보를 가져올 수 있도록 설정
import SwiftUI
import CoreLocation
struct ContentView: View {
@ObservedObject private var locationManger = LocationManager()
var body: some View {
let coordinate = self.locationManger.location != nil ?
self.locationManger.location?.coordinate : CLLocationCoordinate2D()
//리턴되는게 Vstack{} 이라는 것을 알려줌
return VStack {
Text("latitude: \(coordinate!.latitude),
longitude: \(coordinate!.longitude)")
}
.padding()
}
}
시뮬레이션을 돌리면 이렇게 나옵니다.

'Swift & SwiftUI' 카테고리의 다른 글
| CS 193p Lecture 3~4 정리 (0) | 2023.11.22 |
|---|---|
| Networking for beginners (0) | 2023.10.11 |
| Optional Binding, Chaining (0) | 2023.10.09 |
| Grid (0) | 2023.09.18 |
| TextField (0) | 2023.09.10 |