skip to content

Core Location

Core Location reports position through CLLocationManager or CLLocationUpdate.liveUpdates, behind when-in-use or always authorization. Interviewers probe accuracy versus battery and background use.

on this pageshow

explore

questions

6

In Core Location, how does an iOS app ask for when-in-use location permission, and what must its Info.plist contain first?

level: juniorimportance: must knowfreq 75%

answer

  1. a sentence the alert shows
  2. an Info.plist usage description key
  3. status starts as notDetermined
  4. one delegate callback reports every change
  5. instance authorizationStatus since iOS 14

basics

~10 s

Add NSLocationWhenInUseUsageDescription to Info.plist, then call requestWhenInUseAuthorization() on a CLLocationManager while its authorizationStatus is notDetermined. The system prompts once and reports the answer through locationManagerDidChangeAuthorization(_:).

solid answer

~40 s

Core Location shows its permission alert once per app, so the setup has to be right. First add `NSLocationWhenInUseUsageDescription` to Info.plist with a sentence saying why the app needs location; without it the request does nothing. Create a `CLLocationManager`, assign its `delegate` straight away, and when the user taps something that needs location, such as Start Walk, call `requestWhenInUseAuthorization()` if `authorizationStatus` is `.notDetermined`. The answer arrives in `locationManagerDidChangeAuthorization(_:)`, which also fires with the initial status after the manager is created and whenever the user changes the setting. Switch on `manager.authorizationStatus`: start updates for `.authorizedWhenInUse` or `.authorizedAlways`; for `.denied` or `.restricted` turn the feature off and point to Settings, because asking again shows nothing.

code

swift · 32 lines
swift
import CoreLocation

final class WalkPermission: NSObject, CLLocationManagerDelegate {
    private let manager = CLLocationManager()

    override init() {
        super.init()
        manager.delegate = self  // the initial status arrives in the callback below
    }

    func startWalkTapped() {
        if manager.authorizationStatus == .notDetermined {
            manager.requestWhenInUseAuthorization()
        }
    }

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .authorizedWhenInUse, .authorizedAlways:
            manager.startUpdatingLocation()
        case .denied, .restricted:
            manager.stopUpdatingLocation()  // show a "turn on in Settings" state
        case .notDetermined:
            break  // wait for the user to start a walk
        @unknown default:
            break
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {}
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {}
}

go deeper

for a junior

Recall the Info.plist key, the request method, the five status values and the callback that delivers them. Say that the prompt appears once and why timing matters.

for a middle

Explain why the delegate is set at creation, which thread the callback runs on, and that the callback also reports accuracy changes, the initial state and resumption.

for a senior

Show you can diagnose a missing prompt from the plist, the current status and whether the app was in use, and handle Allow Once reverting to notDetermined.

for a principal

Frame when a feature should ask at all, which usage string wording the team signs off, and why a denial needs a designed fallback rather than a retry.

## What when-in-use authorization grants Core Location keeps the device's position away from every app until the person using it agrees. **When-in-use** authorization lets the app receive location while it is being used: on iOS that means in the foreground and for a short time after it moves to the background. Apple calls it the preferred level because it is better for privacy and battery. The stronger level, **Always**, adds the ability for the system to launch a terminated app for significant-change, visit and region events; most features never need it, and an app reaches it either by upgrading from when-in-use or through a two-prompt flow when it asks for Always directly. For a dog-walking app, showing the walker where they are on the walk screen and finding waiting dogs nearby are when-in-use features. Nothing about them needs the app to run while it is closed. ## The usage description comes first The alert the system shows includes a sentence written by the app. It comes from Info.plist: - `NSLocationWhenInUseUsageDescription` is required for **any** location request, when-in-use or Always. - `NSLocationAlwaysAndWhenInUseUsageDescription` is added on top when the app will also ask for Always. - `NSLocationAlwaysUsageDescription` is deprecated; it only mattered for apps deploying below iOS 11. Apple's guidance is to add every key before making any request. The header for `requestWhenInUseAuthorization()` states that without `NSLocationWhenInUseUsageDescription` the method does nothing, because the app is assumed not to support when-in-use authorization. There is no generic fallback text. ## Asking at the right moment The prompt appears only once, so the timing decides how often people say yes: 1. Create one `CLLocationManager` and set its `delegate` immediately. Apple notes that the system reports the current status to the delegate after the manager finishes initializing, so a delegate assigned late can miss that first call. 2. Wait until the person engages a location feature, such as tapping Start Walk. A prompt at launch, with no visible reason, is far more likely to be denied. 3. If `authorizationStatus` is `.notDetermined`, call `requestWhenInUseAuthorization()`. The call returns immediately; it has no return value and does not throw. 4. Handle the result in `locationManagerDidChangeAuthorization(_:)` and start location services only when the status allows it. The delegate methods run on the run loop of the thread that created the manager, which is why managers are normally created on the main thread. ## Reading the result `authorizationStatus` is an **instance property** of `CLLocationManager` since iOS 14; the old class method `CLLocationManager.authorizationStatus()` and the delegate method `locationManager(_:didChangeAuthorization:)` were deprecated in iOS 14 in favour of the property and `locationManagerDidChangeAuthorization(_:)`. The new callback fires when either `authorizationStatus` or `accuracyAuthorization` changes, when a suspended app starts running again, and with the initial state. | Status | Meaning | What the app does | |---|---|---| | `.notDetermined` | No choice yet | Request at the moment of use | | `.authorizedWhenInUse` | Allowed while in use | Start the service | | `.authorizedAlways` | Allowed at any time | Start the service | | `.denied` | The user refused, or Location Services is off system-wide | Disable the feature, offer Settings | | `.restricted` | Blocked by restrictions the user may not control | Disable the feature, no Settings hint | If the person picks **Allow Once**, the app gets a temporary when-in-use authorization that expires when the app is no longer in use and returns to `.notDetermined`, so the next walk asks again. ## Common mistakes - Calling `requestWhenInUseAuthorization()` after a denial and expecting a second prompt. Once the status is no longer `.notDetermined`, the call does nothing. - Treating `.restricted` like `.denied`. A restricted user may not be able to change the setting at all, so a Go to Settings button only frustrates them. - Calling the request while the app is not in use; the header says the method does nothing then. - Starting updates before the status is known, then reading a `nil` `location` as an error. - Reading the deprecated class method in new code: the compiler warns, and the instance property is the one that matches each manager's callbacks. A newer path exists too: iterating `CLLocationUpdate.liveUpdates()` makes Core Location request when-in-use authorization if the app has not asked yet, and the usage string rule is identical.

  • The walk screen calls requestWhenInUseAuthorization() but no alert ever appears; what do you check?
    Check that `NSLocationWhenInUseUsageDescription` is in the built app's Info.plist; without it the request does nothing. Then read `authorizationStatus`: if it is already `.denied`, `.restricted` or authorized, the call does nothing because the person already answered. Finally confirm the call happens while the app is in use, not from a background callback, since the header says the method does nothing when the app is not in use.
  • Later the app wants Always authorization for an automatic visit log; how does it ask, and what limits that request?
    Add `NSLocationAlwaysAndWhenInUseUsageDescription` alongside the when-in-use key, then call `requestAlwaysAuthorization()` while holding when-in-use, ideally when the walker switches the feature on. Core Location allows that upgrade request one time only; later calls do nothing. If the walker chose Allow Once, Core Location ignores it. The alert offers Keep Only While Using or Change to Always Allow, and keeping when-in-use sends no delegate callback.

  • Calling requestWhenInUseAuthorization() again after Don't Allow shows the prompt a second time.
  • Without a usage description, iOS just shows a generic location prompt.
  • Asking for location at first launch is best so it is ready when needed.
  • Denied and restricted are the same, so both get a Go to Settings button.
  • The class method CLLocationManager.authorizationStatus() is the current way to read the status.
open as a page

In Core Location, how does CLLocationUpdate.liveUpdates differ from CLLocationManager's delegate updates, and how does each trade accuracy against battery?

level: middleimportance: must knowfreq 62%

basics

~10 s

liveUpdates(:), added in iOS 17, returns an async sequence of CLLocationUpdate values tuned by one LiveConfiguration. The delegate API pushes arrays to locationManager(:didUpdateLocations:) and is tuned with desiredAccuracy, distanceFilter, activityType and automatic pausing.

open as a page

A dog-walking app's route recording stops minutes after the walker locks the iPhone; what in Core Location do you check, and in what order?

level: seniorimportance: must knowfreq 58%

basics

~10 s

Check that UIBackgroundModes includes location, that a CLLocationManager sets allowsBackgroundLocationUpdates to true or a liveUpdates loop holds a CLBackgroundActivitySession started in the foreground, and that automatic pausing has not ended updates.

open as a page

In Core Location, when a walker grants only approximate location, how do you request temporary full accuracy, and why can that request fail?

level: middleimportance: should knowfreq 45%

basics

~10 s

When accuracyAuthorization is .reducedAccuracy, call requestTemporaryFullAccuracyAuthorization(withPurposeKey:) with a key from NSLocationTemporaryUsageDescriptionDictionary. It fails with CLError.Code.promptDeclined if the key is missing, the app already has full accuracy, or it runs in the background.

open as a page

With Core Location's CLMonitor, how do you detect a walk entering the park, and which limits and relaunch rules apply?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Open a monitor with await CLMonitor("name"), add a CLMonitor.CircularGeographicCondition with an identifier, and iterate monitor.events for .satisfied and .unsatisfied states. An app may monitor at most 20 conditions, and after a relaunch it must reopen the same-named monitor.

open as a page

As lead of a dog-walking iOS app, how do you decide which Core Location authorization, accuracy and background mechanism each location feature asks for?

level: principalimportance: should knowfreq 30%

basics

~20 s

Give each feature the weakest grant that works: when-in-use plus a background activity session for walks, reduced or temporary full accuracy for nearby lists, and Always only for an unattended visit log, requested when it is enabled.

open as a page