swiftxcodeswiftuicllocation

How to get Current Location with SwiftUI?


Trying to get current location with using swiftUI. Below code, couldn't initialize with didUpdateLocations delegate.

class GetLocation : BindableObject {
    var didChange = PassthroughSubject<GetLocation,Never>()

    var location : CLLocation {
        didSet {
            didChange.send(self)
        }
    }
    init() {}
}

Solution

  • This code below works (Not production ready). Implementing the CLLocationManagerDelegate works fine and the lastKnownLocation is updated accordingly.

    Don't forget to set the NSLocationWhenInUseUsageDescription in your Info.plist

    class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
        private let manager = CLLocationManager()
        var lastKnownLocation: CLLocation?
    
        func startUpdating() {
            manager.delegate = self
            manager.requestWhenInUseAuthorization()
            manager.startUpdatingLocation()
        }
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            print(locations)
            lastKnownLocation = locations.last
        }
    
        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            if status == .authorizedWhenInUse {
                manager.startUpdatingLocation()
            }
        }
    }