Getting the User's Location
Receive location updates with CLLocationManager.
Getting the User's Location is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Starting Location Updates
Once authorized, call startUpdatingLocation() to begin receiving a continuous stream of fixes. The manager delivers them through the delegate. Always call stopUpdatingLocation() when you no longer need them to save battery.
manager.startUpdatingLocation()
// ... later
manager.stopUpdatingLocation()Receiving Locations in the Delegate
New fixes arrive in locationManager(_:didUpdateLocations:). The array is ordered oldest-to-newest, so the last element is the most recent location.
func locationManager(_ m: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
guard let latest = locations.last else { return }
print(latest.coordinate.latitude, latest.coordinate.longitude)
}The CLLocation Object
Each fix is a CLLocation containing far more than coordinates: coordinate, altitude, speed, course, timestamp, and accuracy values. Inspect these to decide whether a fix is good enough.
func describe(_ loc: CLLocation) {
print("lat:", loc.coordinate.latitude)
print("lon:", loc.coordinate.longitude)
print("alt:", loc.altitude)
print("when:", loc.timestamp)
}Desired Accuracy
Set desiredAccuracy to tell Core Location how precise you need fixes. Higher accuracy uses more power. Constants include kCLLocationAccuracyBest, kCLLocationAccuracyNearestTenMeters, kCLLocationAccuracyHundredMeters, and kCLLocationAccuracyKilometer.
manager.desiredAccuracy = kCLLocationAccuracyNearestTenMetersDistance Filter
Use distanceFilter to suppress updates until the device has moved a minimum number of meters. This reduces noise and saves power for use cases that do not need every tiny movement.
manager.distanceFilter = 50 // metersJudging Fix Quality
The horizontalAccuracy property is the radius (in meters) of confidence. A negative value means the fix is invalid. Also reject stale fixes by checking how old the timestamp is.
func isUsable(_ loc: CLLocation) -> Bool {
guard loc.horizontalAccuracy >= 0 else { return false }
let age = -loc.timestamp.timeIntervalSinceNow
return age < 15 && loc.horizontalAccuracy < 100
}Requesting a One-Shot Location
If you only need a single fix (not a stream), call requestLocation(). The manager delivers one location to the delegate, then automatically stops. It is more battery-friendly than starting continuous updates.
manager.requestLocation()Handling Location Errors
Failures arrive in locationManager(_:didFailWithError:). A common one is CLError.locationUnknown, which is often transient — keep waiting. CLError.denied means permission was revoked and you should stop.
func locationManager(_ m: CLLocationManager,
didFailWithError error: Error) {
if let clErr = error as? CLError, clErr.code == .denied {
m.stopUpdatingLocation()
}
}Significant-Change Monitoring
For low-power, coarse tracking that can wake your app in the background, use startMonitoringSignificantLocationChanges(). It only fires after the device moves roughly 500 meters and is ideal for region-aware features.
manager.startMonitoringSignificantLocationChanges()Heading and Course
For compass features, startUpdatingHeading() delivers magnetic/true heading via locationManager(_:didUpdateHeading:). Note CLLocation.course (direction of travel) differs from heading (device orientation).
func locationManager(_ m: CLLocationManager,
didUpdateHeading newHeading: CLHeading) {
print("Heading:", newHeading.trueHeading)
}Computing Distance Between Points
CLLocation can measure straight-line distance to another location with distance(from:), returning meters. This is handy for proximity logic without any map UI.
let a = CLLocation(latitude: 41.0, longitude: 28.9)
let b = CLLocation(latitude: 41.1, longitude: 29.0)
let meters = a.distance(from: b)
print("Distance:", meters)Quick Check: Getting Location
Check your grasp of receiving fixes.
Recap: Getting the User's Location
You now know how to obtain coordinates:
startUpdatingLocation()for a stream,requestLocation()for one fix.- Read the newest fix from
locations.lastin the delegate. - Tune
desiredAccuracyanddistanceFilterfor power vs precision. - Validate
horizontalAccuracyandtimestampbefore using a fix.
Frequently asked questions
Is the “Getting the User's Location” lesson free?
Yes — the full text of “Getting the User's Location” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Getting the User's Location”?
Receive location updates with CLLocationManager. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Getting the User's Location” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Requesting Location Authorization
- Getting the User's Location
- Displaying Maps in SwiftUI
- Geocoding and Regions