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:

  • NSLocationWhenInUseUsageDescription for basic location access
  • NSLocationAlwaysAndWhenInUseUsageDescription for background location access

Constants

  • Shared singleton instance of LocationManager for app-wide coordination

    Declaration

    Swift

    @MainActor
    public static let shared: LocationManager

CLLocationManagerDelegate

  • Called when the authorization status changes

    Declaration

    Swift

    @MainActor
    public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager)

    Parameters

    manager

    The location manager whose authorization changed

  • Called when location data becomes available

    Declaration

    Swift

    @MainActor
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

    Parameters

    manager

    The location manager providing the update

    locations

    Array of location objects in chronological order

  • Called when location request fails

    Declaration

    Swift

    @MainActor
    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)

    Parameters

    manager

    The location manager that encountered the error

    error

    The error that occurred during location request