[swift] Swift UI에서 사용자의 현재 위치를 추적하는 방법에 대해 알려주세요.

Swift UI에서 사용자의 현재 위치를 추적하는 방법은 Core Location 프레임워크를 사용하는 것입니다. Core Location은 GPS, Wi-Fi, 모바일 네트워크 등 다양한 방법을 통해 사용자의 위치를 가져올 수 있는 기능을 제공합니다.

먼저, 프로젝트에서 Core Location 프레임워크를 추가해야 합니다. 프로젝트 타겟을 선택하고, Build Phases 섹션에서 Link Binary With Libraries 항목을 클릭한 후 CoreLocation.framework를 추가합니다.

다음으로, 사용자의 위치를 추적하는 코드를 작성해보겠습니다.

import SwiftUI
import CoreLocation

struct ContentView: View {
    @State private var userLocation: CLLocation?

    var body: some View {
        Text("현재 위치: \(userLocation?.coordinate.latitude ?? 0), \(userLocation?.coordinate.longitude ?? 0)")
            .onAppear {
                startLocationUpdates()
            }
    }

    func startLocationUpdates() {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }
    }
}

extension ContentView: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            userLocation = location
        }
    }
}

위의 코드에서는 Core Location 프레임워크를 사용하여 사용자의 위치를 추적합니다. ContentView에는 @State 변수로 userLocation을 정의하였고, 이 변수를 통해 사용자의 위치를 표시하고 있습니다.

startLocationUpdates() 함수에서는 CLLocationManager 객체를 생성하고, delegate를 설정한 후 사용자의 위치 권한을 요청합니다. 사용자가 위치 권한을 허용한 경우, 정확도를 설정하고 위치 업데이트를 시작합니다.

extension으로 CLLocationManagerDelegate를 확장하였고, locationManager(_:didUpdateLocations:) 메서드를 구현하여 사용자의 위치가 업데이트될 때마다 userLocation을 업데이트합니다.

위의 코드를 실행하면, 사용자의 위치가 업데이트될 때마다 Text 뷰에 위치 정보가 표시됩니다. 사용자의 위치 추적을 멈추려면, locationManager.stopUpdatingLocation()을 사용하면 됩니다.

참고 자료: