Get user location, track movement, and monitor regions/beacons.
Core Location Overview
# Framework: CoreLocation
# Import: import CoreLocation
# Permissions: NSLocationWhenInUseUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescriptionPermissions
<!-- Info.plist -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs location access to show nearby places</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs background location for geofencing</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs background location for geofencing (iOS 10)</string>Location Manager
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
static let shared = LocationManager()
private let manager = CLLocationManager()
@Published var currentLocation: CLLocation?
@Published var authorizationStatus: CLAuthorizationStatus = .notDetermined
@Published var error: Error?
@Published var isUpdating = false
private override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.distanceFilter = 10 // meters
// For background updates
manager.allowsBackgroundLocationUpdates = true
manager.pausesLocationUpdatesAutomatically = false
manager.showsBackgroundLocationIndicator = true
}
// Request permission
func requestPermission(_ type: PermissionType = .whenInUse) {
switch type {
case .whenInUse:
manager.requestWhenInUseAuthorization()
case .always:
manager.requestAlwaysAuthorization()
}
}
enum PermissionType {
case whenInUse, always
}
// Start/stop updates
func startUpdating() {
guard authorizationStatus == .authorizedWhenInUse || authorizationStatus == .authorizedAlways else {
requestPermission()
return
}
isUpdating = true
manager.startUpdatingLocation()
}
func stopUpdating() {
isUpdating = false
manager.stopUpdatingLocation()
}
// One-time location
func requestLocation() {
manager.requestLocation()
}
// Delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
currentLocation = location
error = nil
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.error = error
print("Location error: \(error)")
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
authorizationStatus = manager.authorizationStatus
switch manager.authorizationStatus {
case .authorizedWhenInUse, .authorizedAlways:
if isUpdating { manager.startUpdatingLocation() }
case .denied, .restricted:
stopUpdating()
case .notDetermined:
break
@unknown default:
break
}
}
}SwiftUI Integration
struct LocationView: View {
@StateObject private var locationManager = LocationManager.shared
@State private var tracking = false
var body: some View {
VStack(spacing: 20) {
// Status
HStack {
Circle()
.fill(statusColor)
.frame(width: 12, height: 12)
Text(statusText)
Spacer()
}
.padding()
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
// Coordinates
if let location = locationManager.currentLocation {
VStack(alignment: .leading, spacing: 8) {
Text("Latitude: \(location.coordinate.latitude, specifier: "%.6f")")
Text("Longitude: \(location.coordinate.longitude, specifier: "%.6f")")
Text("Accuracy: ±\(location.horizontalAccuracy, specifier: "%.1f")m")
Text("Altitude: \(location.altitude, specifier: "%.1f")m")
Text("Speed: \(location.speed >= 0 ? String(format: "%.1f", location.speed) : "N/A") m/s")
}
.font(.system(.body, design: .monospaced))
.padding()
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
}
// Controls
HStack(spacing: 20) {
Button(tracking ? "Stop" : "Start") {
tracking.toggle()
tracking ? locationManager.startUpdating() : locationManager.stopUpdating()
}
.buttonStyle(.borderedProminent)
.disabled(locationManager.authorizationStatus != .authorizedWhenInUse &&
locationManager.authorizationStatus != .authorizedAlways)
Button("Request Once") {
locationManager.requestLocation()
}
.buttonStyle(.bordered)
}
// Permission button
if locationManager.authorizationStatus == .notDetermined {
Button("Request Permission") {
locationManager.requestPermission()
}
.buttonStyle(.borderedProminent)
} else if locationManager.authorizationStatus == .denied {
Button("Open Settings") {
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
}
.buttonStyle(.bordered)
}
if let error = locationManager.error {
Text("Error: \(error.localizedDescription)")
.foregroundColor(.red)
.font(.caption)
}
}
.padding()
}
var statusColor: Color {
switch locationManager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse: return .green
case .denied, .restricted: return .red
default: return .orange
}
}
var statusText: String {
switch locationManager.authorizationStatus {
case .authorizedAlways: return "Always Authorized"
case .authorizedWhenInUse: return "When In Use Authorized"
case .denied: return "Denied"
case .restricted: return "Restricted"
case .notDetermined: return "Not Determined"
@unknown default: return "Unknown"
}
}
}Geofencing
extension LocationManager {
// Add geofence
func addGeofence(center: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String) {
guard authorizationStatus == .authorizedAlways else {
print("Geofencing requires Always permission")
return
}
let region = CLCircularRegion(
center: center,
radius: min(radius, manager.maximumRegionMonitoringDistance),
identifier: identifier
)
region.notifyOnEntry = true
region.notifyOnExit = true
manager.startMonitoring(for: region)
print("Started monitoring: \(identifier)")
}
func removeGeofence(identifier: String) {
for region in manager.monitoredRegions where region.identifier == identifier {
manager.stopMonitoring(for: region)
print("Stopped monitoring: \(identifier)")
}
}
func removeAllGeofences() {
for region in manager.monitoredRegions {
manager.stopMonitoring(for: region)
}
}
}
// Geofence delegate methods
extension LocationManager {
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("Entered region: \(region.identifier)")
// Post notification, update UI, etc.
NotificationCenter.default.post(
name: .geofenceEvent,
object: nil,
userInfo: ["region": region.identifier, "event": "enter"]
)
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("Exited region: \(region.identifier)")
NotificationCenter.default.post(
name: .geofenceEvent,
object: nil,
userInfo: ["region": region.identifier, "event": "exit"]
)
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
print("Monitoring failed for \(region?.identifier ?? "unknown"): \(error)")
}
}
extension Notification.Name {
static let geofenceEvent = Notification.Name("geofenceEvent")
}Beacon Ranging
import CoreLocation
class BeaconManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
@Published var beacons: [CLBeacon] = []
override init() {
super.init()
manager.delegate = self
}
func startRanging(uuid: UUID, major: CLBeaconMajorValue? = nil, minor: CLBeaconMinorValue? = nil) {
let constraint: CLBeaconIdentityConstraint
if let major = major, let minor = minor {
constraint = CLBeaconIdentityConstraint(uuid: uuid, major: major, minor: minor)
} else if let major = major {
constraint = CLBeaconIdentityConstraint(uuid: uuid, major: major)
} else {
constraint = CLBeaconIdentityConstraint(uuid: uuid)
}
let beaconRegion = CLBeaconRegion(beaconIdentityConstraint: constraint, identifier: "beacon-region")
manager.startMonitoring(for: beaconRegion)
manager.startRangingBeacons(satisfying: constraint)
}
func stopRanging() {
for region in manager.monitoredRegions {
manager.stopMonitoring(for: region)
}
manager.stopRangingBeacons(satisfying: CLBeaconIdentityConstraint(uuid: UUID()))
}
func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
self.beacons = beacons
}
func locationManager(_ manager: CLLocationManager, didFailRangingFor beaconConstraint: CLBeaconIdentityConstraint, error: Error) {
print("Ranging failed: \(error)")
}
}
// Beacon proximity
extension CLBeacon {
var proximityDescription: String {
switch proximity {
case .immediate: return "Immediate (< 0.5m)"
case .near: return "Near (0.5-3m)"
case .far: return "Far (> 3m)"
case .unknown: return "Unknown"
@unknown default: return "Unknown"
}
}
}Background Location
// Info.plist requirements:
// - UIBackgroundModes: location
// - NSLocationAlwaysAndWhenInUseUsageDescription
class BackgroundLocationManager: LocationManager {
override init() {
super.init()
// Enable background updates
manager.allowsBackgroundLocationUpdates = true
manager.pausesLocationUpdatesAutomatically = false
manager.showsBackgroundLocationIndicator = true
// Activity type for better battery
manager.activityType = .fitness // or .automotiveNavigation, .otherNavigation
}
// Significant location changes (low power)
func startSignificantLocationChanges() {
manager.startMonitoringSignificantLocationChanges()
}
func stopSignificantLocationChanges() {
manager.stopMonitoringSignificantLocationChanges()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
super.locationManager(manager, didUpdateLocations: locations)
// Handle background location updates
if UIApplication.shared.applicationState == .background {
print("Background location update: \(locations.last!)")
// Schedule local notification, upload to server, etc.
}
}
}Distance & Bearing
extension CLLocation {
// Distance in meters
func distance(to location: CLLocation) -> CLLocationDistance {
distance(from: location)
}
// Bearing in degrees (0 = North)
func bearing(to location: CLLocation) -> Double {
let lat1 = coordinate.latitude * .pi / 180
let lon1 = coordinate.longitude * .pi / 180
let lat2 = location.coordinate.latitude * .pi / 180
let lon2 = location.coordinate.longitude * .pi / 180
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
let bearing = atan2(y, x) * 180 / .pi
return (bearing + 360).truncatingRemainder(dividingBy: 360)
}
}
// Geofence check
func isInsideGeofence(userLocation: CLLocation, center: CLLocationCoordinate2D, radius: CLLocationDistance) -> Bool {
let centerLocation = CLLocation(latitude: center.latitude, longitude: center.longitude)
return userLocation.distance(from: centerLocation) <= radius
}Location Settings by Use Case
// Configure for different use cases
enum LocationUseCase {
case navigation // High accuracy, frequent updates
case fitness // High accuracy, distance filter
case geofencing // Background, significant changes
case weather // Low accuracy, infrequent
case findNearby // Balanced
var config: (accuracy: CLLocationAccuracy, distanceFilter: CLLocationDistance, activityType: CLActivityType) {
switch self {
case .navigation:
return (kCLLocationAccuracyBestForNavigation, 1, .automotiveNavigation)
case .fitness:
return (kCLLocationAccuracyBest, 5, .fitness)
case .geofencing:
return (kCLLocationAccuracyHundredMeters, 100, .other)
case .weather:
return (kCLLocationAccuracyThreeKilometers, 1000, .other)
case .findNearby:
return (kCLLocationAccuracyNearestTenMeters, 50, .other)
}
}
func apply(to manager: CLLocationManager) {
manager.desiredAccuracy = config.accuracy
manager.distanceFilter = config.distanceFilter
manager.activityType = config.activityType
}
}Try It
Request permissions. Get current location. Start location updates. Add geofences. Test beacon ranging. Simulate location in Xcode.
# Simulate location: Debug → Simulate Location → Custom
# Or GPX file: Debug → Simulate Location → Add GPX FileLocation features
- Request When In Use and Always permissions
- Display current location with accuracy
- Track location updates in real-time
- Add geofences for home/work
- Show notifications on geofence enter/exit
- Implement beacon ranging
- Test background location updates
Core Location requires explicit permissions. Use appropriate accuracy for use case. Geofencing needs Always permission. Background location requires UIBackgroundModes. Beacons use CLBeaconRegion. Test with Xcode location simulation.