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)")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?