Swift Academy · Lesson

Getting the User's Location

Receive location updates with CLLocationManager.

Lesson 2 of 413 steps

Getting the User's Location is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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 = kCLLocationAccuracyNearestTenMeters

Distance 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 // meters

Judging 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.last in the delegate.
  • Tune desiredAccuracy and distanceFilter for power vs precision.
  • Validate horizontalAccuracy and timestamp before using a fix.
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Getting the User's Location” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Getting the User's Location”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

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

  1. Requesting Location Authorization
  2. Getting the User's Location
  3. Displaying Maps in SwiftUI
  4. Geocoding and Regions
← Back to Swift Academy