How to get Current Location with SwiftUI?

后端 未结 3 987
你的背包
你的背包 2020-12-15 09:07

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

class GetLocation : BindableObject {         


        
3条回答
  •  既然无缘
    2020-12-15 09:23

    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, CLLocationManagerDelegate, BindableObject {
        private let manager: CLLocationManager
        var didChange = PassthroughSubject()
    
        var lastKnownLocation: CLLocation? {
            didSet {
                didChange.send(self)
            }
        }
    
        init(manager: CLLocationManager = CLLocationManager()) {
            self.manager = manager
            super.init()
        }
    
        func startUpdating() {
            self.manager.delegate = self
            self.manager.requestWhenInUseAuthorization()
            self.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()
            }
        }
    }
    

提交回复
热议问题