How do I track location updates and geofences in Swift?

Tracking location updates and geofences in Swift is essential for many applications that need to respond dynamically based on user location. Utilizing Core Location, a framework provided by Apple, you can effectively manage location-based events and updates.

In this example, you'll learn how to set up a location manager to continuously track the user's location and how to create a geofence that triggers an event when the user enters or exits a specified area.

import UIKit import CoreLocation class LocationManager: NSObject, CLLocationManagerDelegate { var locationManager: CLLocationManager! override init() { super.init() locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() setupGeofence() } func setupGeofence() { let geofenceRegionCenter = CLLocationCoordinate2DMake(37.33233141, -122.0312186) let geofenceRegion = CLCircularRegion(center: geofenceRegionCenter, radius: 100, identifier: "Geofence") geofenceRegion.notifyOnEntry = true geofenceRegion.notifyOnExit = true locationManager.startMonitoring(for: geofenceRegion) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } print("Location updated: \(location.coordinate.latitude), \(location.coordinate.longitude)") } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { print("Entered geofence: \(region.identifier)") } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { print("Exited geofence: \(region.identifier)") } }

Location Tracking Geofencing Swift Core Location iOS Development CLLocationManager Location Manager