Swift version: 5.10
Continuous location tracking allows an app to monitor a user’s location even when it is running in the background. This is useful for navigation apps, fitness tracking, and geofencing. However, background location tracking must be used responsibly to preserve battery life and comply with Apple’s privacy guidelines.
Prerequisites
To track location in the background, you need to:
- Request the appropriate location permissions.
- Enable background location updates in Info.plist.
- Configure CLLocationManager for continuous tracking.
- Handle app lifecycle changes to manage background location updates efficiently.
Step 1: Request Location Permissions
First, you must request permission from the user to access their location.
Copied!import CoreLocation class LocationManager: NSObject, CLLocationManagerDelegate { private var locationManager = CLLocationManager() override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.allowsBackgroundLocationUpdates = true locationManager.pausesLocationUpdatesAutomatically = false } func requestLocationPermission() { locationManager.requestAlwaysAuthorization() // Request background tracking permission } func startTracking() { locationManager.startUpdatingLocation() } func stopTracking() { locationManager.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } print("New location: \(location.coordinate.latitude), \(location.coordinate.longitude)") } }
How it works:
- requestAlwaysAuthorization() requests permission for background location updates.
- allowsBackgroundLocationUpdates = true ensures tracking continues in the background.
- pausesLocationUpdatesAutomatically = false prevents iOS from automatically pausing updates.
- startUpdatingLocation() starts tracking continuously.
📌 Call requestLocationPermission() when initializing the app.
Step 2: Modify Info.plist for Background Location Access
To allow background location tracking, update Info.plist by adding:
Copied!<key>NSLocationAlwaysUsageDescription</key> <string>We use your location to track your activity even in the background.</string> <key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>We need continuous access to your location to provide better tracking.</string> <key>NSLocationWhenInUseUsageDescription</key> <string>This app requires location access to function properly.</string> <key>UIBackgroundModes</key> <array> <string>location</string> </array>
Why is this needed?
• NSLocationAlwaysUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription allow continuous tracking.
• UIBackgroundModes with location ensures location tracking continues when the app is backgrounded.
Step 3: Handling App Lifecycle for Continuous Tracking
To prevent tracking from stopping when the app moves to the background, handle app lifecycle changes.
Implementation in AppDelegate:
Copied!func applicationDidEnterBackground(_ application: UIApplication) { LocationManager().startTracking() print("App moved to background - continuing location updates") } func applicationWillTerminate(_ application: UIApplication) { LocationManager().stopTracking() print("App is terminating - stopping location updates") }
How it works:
• Ensures location tracking continues when the app enters the background.
• Stops tracking when the app is about to be terminated to save battery.
Step 4: Detecting Background Location Events Efficiently
To minimize battery consumption, use significant location change monitoring instead of continuous updates.
Using Significant Location Changes Instead of Continuous Updates:
Copied!func startSignificantChangeUpdates() { locationManager.startMonitoringSignificantLocationChanges() } func stopSignificantChangeUpdates() { locationManager.stopMonitoringSignificantLocationChanges() }
Why use this?
• startMonitoringSignificantLocationChanges() updates location only when a major movement is detected, reducing battery drain.
Step 5: Handling Location Tracking Interruptions
iOS may suspend location updates when the app is inactive. Handle interruptions to restart tracking when needed.
Copied!func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Location update failed: \(error.localizedDescription)") if let clError = error as? CLError, clError.code == .denied { print("Permission denied. Requesting again.") requestLocationPermission() } }
How it works:
• Detects and handles errors like location tracking being disabled by the user.
Conclusion
By following these steps, you can enable continuous location tracking in the background:
- Request Always location permission.
- Enable UIBackgroundModes > location in Info.plist.
- Use CLLocationManager with allowsBackgroundLocationUpdates = true.
- Handle app lifecycle changes to maintain tracking.
- Use significant location changes to optimize battery usage.