1

I am developing an app in which i need to update user's location regularly, but i am not able to get location update when the app is suspended or running in background. I have also enabled background location update in capabilities.

viewDidLoad code:

override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        let user=FIRAuth.auth()?.currentUser?.displayName
        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){
            locationManager.requestLocation()
            location=locationManager.location
            locationManager.startUpdatingLocation()
            locationManager.startMonitoringSignificantLocationChanges()
            //updating to database
            ref.child("\(user!)/lat").setValue(location.coordinate.latitude)
            ref.child("\(user!)/long").setValue(location.coordinate.longitude)
            //location=locationManager.location
        }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        location=locations[locations.count-1]
    }

1 Answers1

0

Enable location update -> Background Mode -> Capabilities

I was using this method get location in background. This method write in AppDelegate class

 func getLocation() {
    self.locationManager = CLLocationManager()
    self.locationManager.delegate = self
    if self.locationManager.responds(to: #selector(self.requestAlwaysAuthorization)) {
        self.locationManager.requestAlwaysAuthorization()
    }
    self.locationManager.distanceFilter = kCLDistanceFilterNone
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    if !CLLocationManager.locationServicesEnabled() {
            // location services is disabled, alert user
        var servicesDisabledAlert = UIAlertView(title: "Alert", message: "Location service is disable. Please enable to access your current location.", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
        servicesDisabledAlert.show()
    }
    else {
        self.locationManager.startUpdatingLocation()
    }
}
Nidhi Patel
  • 1,222
  • 11
  • 17