3

I am trying to track the user location in background I have try using when In us with and without always , but every time I minimise the app the location icon disappear I have read in a tutorial it should show blue bar but I am not getting that bar I have also check the background mode for updating the location

  map.showsUserLocation = true
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    // Do any additional setup after loading the view, typically from a nib.
    alwaysAuthorization()
}

func alwaysAuthorization(){
    if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
        locationManager.requestAlwaysAuthorization()
    }
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last
    let region  = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude), span: MKCoordinateSpan (latitudeDelta: 0.2, longitudeDelta: 0.2))
    self.map.region = region
    print("location \(location!.coordinate.latitude) and \(location!.coordinate.longitude)")
}
Nouf
  • 733
  • 1
  • 11
  • 32

3 Answers3

6

this what I was looking for

        locationManager.allowsBackgroundLocationUpdates = true
Nouf
  • 733
  • 1
  • 11
  • 32
2

You can use startMonitoringSignificantLocationChanges() method instead of startUpdatingLocation()

Based on docs:

Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. It should not expect notifications more frequently than once every five minutes. If the device is able to retrieve data from the network, the location manager is much more likely to deliver notifications in a timely manner.

I have used this method once and tested it. It works well with cellular and wi-fi.

Alper
  • 1,415
  • 2
  • 13
  • 20
1

Your question is not clear. Do you have problems running your app in background? Or do you simple expect the blue bar indicating that your app tracks the location in background?

For the latter you need to enable the background location indicator

locationManager.showsBackgroundLocationIndicator = true
zisoft
  • 22,770
  • 10
  • 62
  • 73
  • no it is running the background , but the Indicator disappear after few second if I was not using the "always" and I dont want to use it if possible – Nouf Dec 17 '18 at 12:44