-2

I am building an app that tracks a users location while the app is open and query it with geofire. I would like to keep the location updating from any view controller the user may have open. I am wondering how to do this.

Currently, I have my geofire and location tracking set up in my main view controller. In order to have the location tracking working across all view controllers, do I have to code each individual view controller to track the location, or can I place the code into, for example, the app delegate file?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
dima618
  • 67
  • 11

4 Answers4

1

Put it in app delegate.swift

let locationManager = CLLocationManager()


self.locationManager.requestAlwaysAuthorization() 

// For use in foreground
self.locationManager.requestWhenInUseAuthorization()

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

//Here Get Late long.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}
Khushal iOS
  • 303
  • 2
  • 12
0

You can place the code in AppDelegate. Maybe use a timer while hitting the server so that the performance is optimized

Refer this answer: Location Manager update frequency, iphone

The Pedestrian
  • 460
  • 2
  • 11
0

may be this code will hleps but you have to use this in your all viewcontrollers

var LocationManager = CLLocationManager()
LocationManager.requestWhenInUseAuthorization()

if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() ==  .authorizedAlways){

  print("currentLocation = \(LocationManager.location)")

 }
Chetan Hedamba
  • 229
  • 2
  • 7
0

Use HSLocationManager for infinite location tracking in the active and inactive state.

Location manager that allows getting background location updates every n seconds with desired location accuracy.

Advantage:

  • OS will never kill our app if the location manager is currently running.

  • Give periodically location update when it required(range is between 2 - 170 seconds (limited by max allowed background task time))

  • Customizable location accuracy and time period.

  • Low memory consumption(Singleton class)

  • Less battery draining.
Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65