LocationManager
public class LocationManager : NSObject, ObservableObject, @unchecked Sendable
extension LocationManager: @preconcurrency CLLocationManagerDelegate
LocationManager is responsible for requesting authorization, managing, and collecting device location information.
This class provides a modern, async/await interface for location services built on top of CoreLocation. It handles authorization requests, caching, error handling, and provides both throwing and non-throwing interfaces for different use cases.
Features
- Async/Await Interface: Modern Swift concurrency support
- Automatic Authorization: Handles permission requests transparently
- Location Caching: Reduces battery usage with intelligent caching
- Error Handling: Comprehensive error reporting and recovery
- Privacy Compliance: Respects system privacy settings and user choices
Usage Example
do {
let location = try await LocationManager.shared.requestLocation()
print("Current location: \(location?.coordinate)")
} catch {
print("Location failed: \(error)")
}
Privacy Requirements
Your app’s Info.plist must include appropriate usage descriptions:
NSLocationWhenInUseUsageDescriptionfor basic location accessNSLocationAlwaysAndWhenInUseUsageDescriptionfor background location access
-
Shared singleton instance of LocationManager for app-wide coordination
Declaration
Swift
@MainActor public static let shared: LocationManager
-
Called when the authorization status changes
Declaration
Swift
@MainActor public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager)Parameters
managerThe location manager whose authorization changed
-
Called when location data becomes available
Declaration
Swift
@MainActor public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])Parameters
managerThe location manager providing the update
locationsArray of location objects in chronological order
-
Called when location request fails
Declaration
Swift
@MainActor public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)Parameters
managerThe location manager that encountered the error
errorThe error that occurred during location request
View on GitHub