skip to content

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%

answer

  1. a named, persistent monitor
  2. a circular condition and an identifier
  3. iterate events for state changes
  4. twenty conditions per app
  5. reopen the same name after relaunch

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.

solid answer

~50 s

`CLMonitor` (iOS 17) is an actor scoped by name: `await CLMonitor("WalkGeofences")` creates or opens it, and only one instance with a given name may be open at a time. Add `CLMonitor.CircularGeographicCondition(center:radius:)` with `add(_:identifier:)`, which starts in the `.unknown` state, or `add(_:identifier:assuming:)` to set it. Then keep iterating `monitor.events`; each `Event` carries the `identifier`, a `state` of `.satisfied` or `.unsatisfied`, and a `date`. Conditions persist until removed, and `record(for:)` returns the last event. Apple caps any app at 20 monitored conditions of any type. If the app is not running when a condition changes, iOS tries to launch it, and the app must recreate the monitor with the same name and iterate again; that launch needs Always authorization, and on iOS 18 a held `.always` `CLServiceSession`. Monitoring starts only after the first unlock following a reboot.

code

swift · 25 lines
swift
import CoreLocation

func watchPark() async {
    let monitor = await CLMonitor("WalkGeofences")
    let park = CLMonitor.CircularGeographicCondition(
        center: CLLocationCoordinate2D(latitude: 51.5033, longitude: -0.1196),
        radius: 150
    )
    await monitor.add(park, identifier: "riverside-park")

    do {
        for try await event in await monitor.events {
            switch event.state {
            case .satisfied:
                print("Walk entered \(event.identifier) at \(event.date)")
            case .unsatisfied:
                print("Walk left \(event.identifier)")
            default:
                break
            }
        }
    } catch {
        print("Monitoring ended: \(error)")
    }
}

go deeper

for a junior

Recall that a circular condition plus an identifier on a named CLMonitor reports satisfied and unsatisfied events through an async sequence.

for a middle

Explain the initial unknown state, the assuming variant, persistence and record(for:), and why the events loop must keep running.

for a senior

Plan for the 20-condition cap, relaunch with the same monitor name, first-unlock timing, accuracy limits and the iOS 18 diagnostics that expose each failure.

for a principal

Decide whether geofenced features justify Always authorization, and how the app rotates a large set of places through a small monitoring budget.

## Condition monitoring in Core Location **Condition monitoring**, often called geofencing, lets an app learn when the device enters or leaves an area without running continuous location updates. On iOS the system watches the conditions and wakes the app when one changes between satisfied and unsatisfied. Since iOS 17 the API is `CLMonitor`, a Swift actor. The older `CLLocationManager` path, `startMonitoring(for:)` with a `CLCircularRegion` and the `locationManager(_:didEnterRegion:)` callback, is still present, but the SDK marks it to be deprecated and names `CLMonitor` as its replacement. For the dog-walking app, the park is one circle: when a walk enters it, the app logs the time and updates the walk summary. ## Setting up a monitor 1. Open a monitor by name: `let monitor = await CLMonitor("WalkGeofences")`. The header calls the monitor a name-scoped instance; calling the initializer creates it or opens the existing one. Only one instance with a given name may be open at a time. 2. Describe the area with `CLMonitor.CircularGeographicCondition(center:radius:)`, giving a `CLLocationCoordinate2D` and a radius in meters. 3. Register it with `await monitor.add(park, identifier: "riverside-park")`. The initial state is `.unknown`; `add(_:identifier:assuming:)` lets you assume `.satisfied` or `.unsatisfied` instead, for example when you already know the walker is outside. 4. Iterate `monitor.events` with `for try await` and act on each `CLMonitor.Event`: its `identifier`, `state` and `date`, plus an optional `refinement`. Because `CLMonitor` is an actor, calls such as `add` and `remove(_:)` are awaited from outside it. Apple stresses that you must **keep iterating** the events sequence to learn about changes. ## What persists and what you can query Conditions added to a monitor stay registered until removed; Core Location stores them in a file under the app's container, keyed by the monitor's name. `identifiers` lists what is monitored, and `record(for:)` returns a `CLMonitor.Record` with the condition and its `lastEvent`, or `nil` for an unknown identifier. Because the store lives in the data container, the header asks apps to wait for protected data to become available before creating a monitor, and Apple notes that monitoring only works after the person first unlocks the device following a reboot. ## Limits - **Twenty conditions per app.** Conditions rely on shared hardware, so Core Location prevents any single app from monitoring more than 20 conditions of any type at once. A walking app that wants every park in the city has to rotate a nearby subset. From iOS 18, an event's `conditionLimitExceeded` flag reports that a condition is suspended because too many of that type are monitored. - **Accuracy.** Apple's `CLAccuracyAuthorization` documentation says region monitoring is not available with reduced accuracy; on iOS 18 the event's `accuracyLimited` flag reports that limitation. - **Other iOS 18 diagnostics** on `CLMonitor.Event` include `authorizationDenied`, `insufficientlyInUse`, `conditionUnsupported`, `persistenceUnavailable` and `serviceSessionRequired`. - **State values.** `.unknown`, `.satisfied` and `.unsatisfied`, plus `.unmonitored` from iOS 17.2, so switches need a default case. ## Relaunch and authorization If an iOS app is not running when a condition is satisfied, the system tries to launch it. Apple puts the next step on the app: recreate the monitor **with the same name** and iterate its events. The header adds that Core Location stops monitoring conditions that have an event pending but no `CLMonitor` configured to receive it, so a relaunch that never reopens the monitor silently loses geofencing. | Authorization | Park entry while app runs | Park entry with app terminated | |---|---|---| | When-in-use | Delivered while in use, including during a background activity session | Not launched by the event | | Always | Delivered | System launches the app | | Always on iOS 18, no `.always` `CLServiceSession` held | Delivered while in use | Not delivered while not in use | The authorization table in Apple's guide says only Always lets the system launch a terminated app for region monitoring. On iOS 18, the `CLServiceSession` header adds that an Always app must hold a session requiring `.always` to receive `CLMonitor` events while not in use, and must retake it promptly when relaunched. In practice a when-in-use design covers most walking apps: park entry only matters during a walk, and the walk's background session keeps the monitor's events flowing. Turning a park entry into a user-visible alert without the app is a different tool, a location trigger on a local notification, and is covered with notifications.

  • The app shows a 'walk entered park' badge but nothing happens after the system relaunches it; why?
    After a relaunch the app must reopen the monitor with the same name and iterate `events`. If launch code never creates the `CLMonitor`, the pending event has no receiver, and the header says Core Location then stops monitoring those conditions. Recreate the monitor early in launch, once protected data is available, and start iterating before doing other work.
  • The product wants alerts for 60 parks across the city; how do you fit the 20-condition limit?
    Monitor only the parks near the walker. Keep the 60 in app data, and when position changes meaningfully, from a significant-change update or a live update during a walk, remove far conditions and add the closest ones, staying under 20 including any other conditions the app uses. On iOS 18, watch `conditionLimitExceeded` to catch mistakes.

  • An app can monitor as many park geofences as it likes.
  • Two CLMonitor instances with the same name can run side by side.
  • After a relaunch, events arrive even if the app never reopens its monitor.
  • A when-in-use app is relaunched when the walker enters the park.
  • startMonitoring(for:) with CLCircularRegion is the recommended region API on iOS 17.

Assumes an iOS 17 deployment target built with the iOS 27.1 SDK: CLMonitor is iOS 17, the unmonitored state iOS 17.2, and event diagnostics such as conditionLimitExceeded and CLServiceSession iOS 18.