blog

“How much time do you need?” Debugging iOS Screen Time in Due or Die

Debug iOS Screen Time shields, DeviceActivity timers, FamilyControls authorization, and App Group storage with real failures and fixes from Due or Die.

For Due or Die, my task and accountability app, we wanted to connect Apple's Screen Time permission sheet, its app-selection screen, and a custom shield that asks “How much time do you need?” The user would approve access, choose distracting apps, and get an interruption before opening one while unfinished tasks remained. Choosing a duration should reveal that app immediately; running out of time should bring the shield back.

TL;DR

The host app confirms FamilyControls authorization and saves it alongside app selections, task state, and timed passes in the shared App Group. The shield extensions read that state to decide when to interrupt. When a user chooses a duration, we save a pending pass, register a DeviceActivity monitor whose interval starts at expiry, then remove the app's reminder restriction through ManagedSettings and commit the pass. Monitor callbacks restore the shield at the stored deadline while the host is backgrounded. Reliable shared storage and this ordering keep the separate processes working together; required locks always take priority over extra time.

The app uses React Native and Expo, but this flow depends on native Swift code and Apple's Screen Time frameworks. These were the screens and APIs we wanted to work together:

  1. The permission sheet. Use FamilyControls and AuthorizationCenter.requestAuthorization(for: .individual) to request Screen Time access. Once approved, the host app and its extensions should agree that access is enabled.
  2. The app-selection screen. Present FamilyActivityPicker, save the chosen application tokens in the App Group, and make that selection available to the extensions before reporting that setup is complete.
  3. The “How much time do you need?” shield. Describe the interruption through ShieldConfiguration in ManagedSettingsUI, handle its buttons in ShieldActionDelegate, and change the restrictions in a ManagedSettingsStore. The finished choices are 1 minute, 10 minutes, and Until tomorrow.
  4. The “Time's up” shield. Use a DeviceActivitySchedule and DeviceActivityMonitor callbacks to restore the restriction and show the expired state of the shield, even while the distracting app stays open and Due or Die is backgrounded.

In practice, the handoffs between those APIs broke. The shield sometimes appeared only after reopening Due or Die. Selecting a duration could leave it in place. If an app did open, getting the shield back at expiry was another problem. We also showed permission errors while iOS Settings still showed Screen Time access enabled.

There were several reasons. Our extensions read a process-local authorization value as though it were a confirmed system-wide answer. Our save checks could reject a successful permission approval because UserDefaults.synchronize() returned false. The timer design had to reconcile a one-minute allowance with DeviceActivity's fifteen-minute minimum monitoring interval, and an intermediate schedule could trigger callbacks while registration was still in progress. Finally, accepting a shield button action did not itself remove the restrictions covering the app. Each of those failures needed a separate fix.

The normal flow now works on my physical iPhone: choosing a duration opens the app on the first try, and the shield returns when the allowance expires. The rest of this post traces the failed approaches, the evidence that separated these problems, and the implementation that finally worked.

One screen, several processes

The app uses React Native and Expo, with a custom Swift module and native extensions for iOS enforcement. The screen over the distracting app is an Apple Screen Time shield. It is not a React screen that I can show over another app with a navigation call.

PartResponsibility in this implementation
Main app / FamilyControlsRequest individual authorization, save app selections, and publish task state.
ShieldConfiguration extensionRead shared state and describe the system shield.
ShieldAction extensionHandle a duration selection and attempt to grant access.
DeviceActivityMonitor extensionHandle the native expiry callbacks and restore restrictions.
ManagedSettings storesHold the restrictions requested by the reminder and required-lock systems.
App Group storageShare authorization receipts, selections, sessions, and other enforcement inputs.

A successful action in one process does not mean another process has loaded the same state. A successful settings write does not prove the shield visibly changed. Those distinctions explain much of what follows.

First, define when the interruption belongs there

My first timed-access implementation gated individually selected apps whenever the feature was enabled. The later implementation needed a more precise rule: show the ordinary reminder while unfinished tasks due today or overdue remain. Completed tasks, future tasks, and onboarding sample tasks should not keep it alive.

I reused the task snapshot already shared with the widget instead of creating another task database for this screen. Native code evaluates dates and pending completion receipts when it reads that snapshot. That matters after midnight and when a task is completed through a native action before JavaScript has caught up.

There are also two deliberately different kinds of restriction. An ordinary reminder permits more time. A required task, punishment, work, or focus lock does not. The onboarding demo is a third case: it lasts ten minutes and offers the duration choices even with no ordinary tasks, but it must never override a real required lock.

State, in priority orderExpected result
Required lock activeStrict shield. No timed escape.
Demo active, no required lockAllow a valid per-app pass; otherwise offer the three choices.
Relevant unfinished tasks, reminder enabledAllow a valid pass; otherwise ask for a duration.
Pass expires and reminder still appliesShow the time-up shield and allow another explicit choice.
No relevant tasks, demo, or required lockClear the ordinary reminder and retire its passes.

I also stopped using the presence of a restriction in a ManagedSettings store as the definition of a live lock. That is enforcement output; it can outlast the condition that created it. The shared lock policy now reads the actual persisted deadlines, work windows, focus state, and completion evidence. It can retire an expired store without treating an active punishment as permission to offer extra time.

Shield rendering became read-only too. The early version called reconciliation while deciding what to display, which could acquire a writable App Group lock, save state, and touch monitor APIs. The current configuration extension only reads and classifies. Writes belong in the host, action handler, and monitor paths. Rendering the question should not itself change its answer.

Attempt one: count active usage

The initial implementation offered 2, 5, or 10 minutes of active use. It registered an app-specific DeviceActivityEvent with a usage threshold inside a monitoring window ending at midnight. Leaving the app was intended to preserve the remainder. The threshold and the monitoring window were separate concepts.

// Original approach: a usage allowance inside a longer schedule.
let event = DeviceActivityEvent(
  applications: [application],
  threshold: DateComponents(minute: minutes),
  includesPastActivity: false
)

try center.startMonitoring(activity, during: schedule, events: [eventName: event])

Apple's monitoring interval has a fifteen-minute minimum. The original code used at least sixteen minutes, backdating the start near midnight and retrying with a longer window if necessary. It preserved the selected usage threshold rather than silently turning a two-minute allowance into a fifteen-minute allowance.

That approach encoded the original product behavior, but the behavior changed. I wanted an elapsed-time break: choose one minute and the deadline remains one minute away even if you switch apps or lock the phone. The choices became one minute, ten minutes, or the next local midnight. This was a change in semantics, not just a different way to implement the same timer. Old usage-based passes are retired rather than reinterpreted as elapsed passes.

One useful warning from reviewing this history: an older internal document still described the active-use version after the code had moved on. Check the implementation and migration policy before borrowing a timer design from your own documentation.

Attempt two: make the end warning expire the pass

A one-minute elapsed deadline still cannot be represented as a one-minute DeviceActivity interval. An intermediate recovery design used a longer, already-ongoing interval: its end warning targeted the selected expiry, and the interval end targeted five seconds later. Short allowances required backdating the interval start to meet the minimum length.

The arithmetic produced the requested 60/65-second targets. The registration shape was a problem. Apple documents that an extension can begin receiving callbacks immediately if startMonitoring registers an ongoing interval. Our registration and callback paths could both reach shared-state and shield operations while the original action was still waiting for registration to finish.

This was a concrete reentrancy risk, but I cannot claim it was the captured cause of that particular device failure: we did not have the necessary grant trace. What we did know was that selecting any of the three choices on the installed build left the shield in place, without a useful error. Correct deadline math had not established a working opening flow.

Attempt three: schedule the interval to start at expiry

The current design moves the whole monitoring interval into the future. The selected deadline is the interval's start. The interval lasts sixteen minutes. Its end warning is fifteen minutes and fifty-five seconds before its end, placing that warning five seconds after the selected deadline. Apple's warningTime documentation explains how warnings are positioned relative to the boundaries.

// Simplified from the production deadline policy.
let intervalStart = expiry
let intervalEnd = expiry.addingTimeInterval(16 * 60)
let warning = DateComponents(minute: 15, second: 55)

let schedule = DeviceActivitySchedule(
  intervalStart: utcComponents(intervalStart),
  intervalEnd: utcComponents(intervalEnd),
  repeats: false,
  warningTime: warning
)

try center.startMonitoring(activity, during: schedule)

Here utcComponents stands for our helper that supplies a full Gregorian date, seconds, calendar, and UTC time zone. This is an excerpt, not a complete grant implementation. No usage-threshold event is registered for these elapsed passes. The start-warning callback is not used to expire them.

A one-minute allowance prepared at 12:00:00
  1. Save pending pass, register future monitor, then unshield.
  2. intervalDidStart: primary expiry.
  3. intervalWillEndWarning: recovery attempt.
  4. intervalDidEnd: later fallback.

This meets the minimum interval without registering inside the main interval. The callbacks reconcile the stored deadline rather than granting time. Unique session IDs prevent a delayed callback for an old pass from ending a newer one. Callbacks received during pending registration are guarded against reentering shield writes, while abandoned pending records can still expire.

Finite deadlines are rounded up to the next second, adding less than a second at preparation. Until tomorrow is calculated with the local calendar's next day boundary, then encoded as an absolute instant. It does not mean “24 hours from now,” especially around daylight-saving changes.

These are requested callback times. My confirmation that normal expiry works on the phone does not prove iOS always delivers either callback at an exact second, or that the forced recovery case has passed. The five-second spacing belongs to our schedule; actual delivery belongs to iOS.

“Open app” meant two different things

Revealing the distracting app and opening Due or Die are separate operations. After a successful timed grant, the target app is already underneath the shield. Our job is to remove its reminder restriction and complete the action with .none. That response means no additional system action is required; it does not remove a restriction by itself.

A strict lock's navigation button instead takes the user back to Due or Die. Apple's .openParentalControlsApp response supports that on iOS 26.5 and later. It opens the shielding app, not the distracting app. The older-version fallback closes the distracting app and leaves the restriction in place.

Duration menus have their own availability boundary: secondaryButtonSubmenuItems arrived in iOS 26.4 and supports up to three choices. Earlier supported versions use our two-button picker: one button cycles the displayed duration, and an explicit primary-button action grants that displayed choice. Navigation and cancellation must never be interpreted as accepting a duration.

Cached shields make that last rule especially useful. A button can outlive the state that rendered it. We classify the current state again and use .defer to redraw when an old menu no longer matches the current lock. Repeated taps reuse a valid allowance; they do not silently reset its deadline.

Granting access became a transaction

Saving a pass and hoping a background timer would be registered later was not acceptable. Neither was waiting forever inside a shield action. The current path has a two-second response budget and this ordering:

  1. Check eligibility and persist a unique pending session. Pending sessions grant no exemption.
  2. Leave the shared-state lock, drain obsolete timer registrations, and register the new native monitor.
  3. Reacquire state and recheck the request deadline, session generation, eligibility, and real locks.
  4. Apply the candidate exemption, keeping the on-disk session pending until the shield write returns.
  5. Persist the committed pass and complete the shield action exactly once.

Monitor start, stop, and inventory calls run outside the cross-process writer lock. Timed expiry callbacks reconcile stored state and restrictions without querying or reconfiguring monitor registrations. A separate response lock is never held across storage or SDK calls, so the watchdog can reply even when those operations stall. The shared writer lock also has a bounded wait rather than blocking a tap indefinitely.

If timeout wins, the handler replies before doing cleanup, rejects a late success, and rolls back only that request's generation. A synchronous Apple IPC call already in flight cannot be canceled, so its eventual result still needs reconciliation. For a quick registration failure, we save the explanation before replying with a redraw. That fixed the especially frustrating case where a choice appeared to do nothing and the error had not been saved yet.

Cleanup cannot depend entirely on work after the reply; the extension may be suspended. Obsolete monitors are queued persistently and retired before the next registration. Apple's twenty-activity limit is shared by the app and its extensions, so leaked registrations can prevent later passes. We protect live allowances and required-lock monitors rather than evicting a real punishment to make room for a break.

FamilyControls authorization: permission was enabled, but our check failed

The revised schedule still did not make the app open on the affected iPhone. It did produce a more useful failure: Screen Time needed approval, despite access being enabled in Settings. A diagnostic report recorded lastGrantFailure.phase: "grant_ineligible"and no sessions despite using the revised schedule. That attempt had stopped at eligibility, before session preparation or timer registration. More timer tuning would not address that recorded failure.

The old grant code read AuthorizationCenter.shared.authorizationStatus from the shield extension's background registration queue. Other reconciliation paths made similar direct reads. Apple's authorizationStatus contract says the initial value is .notDetermined, it is initialized through an authorization request, and it must be accessed on the main queue. A newly running extension's initial value was not reliable evidence that the user had revoked access.

We had not captured the precise enum value from the failing extension, so the initialization timing remains an inference. The failed eligibility check was captured. The threading and initialization assumptions in our code were concrete problems worth removing.

I moved live authorization requests and observation into the host app on MainActor. It publishes confirmed results into the App Group before resolving the permission or status request. The action and monitor extensions consume that receipt instead of initializing their own authorization centers for every decision.

// The policy, in abbreviated form:
switch confirmedHostResult {
case .approved:
  persistApprovalReceipt()
case .denied:
  persistDenialAndRetirePasses()
case .notDetermined:
  break // An initializing process must not overwrite a confirmed result.
}

Those helper names summarize the policy rather than providing a drop-in implementation. The production host also shares concurrent requests, refreshes existing setups on activation, observes changes, and prevents an older asynchronous completion from overwriting a newer observation. Cancellation requires an explicit retry; transient automatic failures back off.

A saved approval receipt is application state, not a replacement permission system. DeviceActivity still has to accept registration before access can be committed. An explicit denial supersedes an old approval. The distinction we needed was between confirmed denial and a process that had not finished establishing its local state.

Signing permission and runtime permission are separate checks

Family Controls also requires the correct capabilities and signing setup. Apple's distribution entitlement guidance covers the app and its Screen Time extensions. Main-app approval does not establish that every extension is correctly configured. App Group membership also has to match the processes that share state.

We inspected the affected app's existing IPA to check its signing configuration. The host, ShieldAction, ShieldConfiguration, and monitor binaries had signed Family Controls and the intended App Group. Their embedded profiles matched, the identifiers and team lined up, and the extensions contained the shared controller. That ruled out missing declared or signed entitlements in that inspected artifact. It did not prove runtime authorization or callback delivery was healthy.

This is the distinction I would check early: developer capability, signed binary and profile, user authorization, and our persisted understanding of authorization are separate layers. “Screen Time permission is broken” was too broad a diagnosis to help.

App Group storage: a save check rejected successful authorization

In a later device test, I approved Apple's permission sheet and then got another error: “Screen Time access is updating. Try again.” This time the persistent diagnostic journal let us see the sequence. The already-approved repeat request completed successfully in roughly three milliseconds. Then our receipt save was rejected:

authorization_request_finished
  requestSucceeded: true

authorization_receipt
  status: approved
  confirmedStatus: approved
  accepted: false

state_sync_failed / save_failed
  operation: sessions_sync

This is a condensed transcription of the recorded fields, not a complete raw report. The App Group container was available. The separate diagnostic file journal had no write failures. There were no sessions, selected apps, or registered monitors in that snapshot.

Our critical save functions used the Boolean from UserDefaults.synchronize() as their commit acknowledgment. A false result made our code reject the authorization receipt and abort session reconciliation, even after the system authorization request succeeded. The report did not explain why the preferences service returned false, and it did not prove those preference writes were durable.

Apple explicitly says synchronize is unnecessary and should not be used. The repair was to stop basing these critical records on that call. Simply ignoring an error and claiming everything saved would have hidden the distinction we needed to preserve.

Authorization, app selection, sessions, and the duration picker now use a shared state store backed by atomic files in the App Group. Writes throw on failure, and the caller waits for that operation to complete before reporting success. Writers use the existing cross-process lock; readers read the canonical files without needing a writable lock.

// Excerpt from the critical-state store on iOS.
try data.write(
  to: recordURL,
  options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]
)

// Compatibility mirror for older consumers, after the canonical write.
defaults.set(data, forKey: legacyKey)

That excerpt shows the binary-data records; the authorization mirror keeps its older dictionary shape. A missing canonical file may migrate legacy defaults under the writer lock. Once a canonical file exists, it wins. An unreadable or corrupt file must not resurrect a stale pass from defaults. An empty saved sessions file is meaningful: it says those passes were cleared.

App selection follows the same completion rule. The picker persists its selection and reconciles enforcement on the worker queue before resolving success. Onboarding checks that demo setup returned a configured gate before advancing. A “Done” button cannot mean “we queued the save and hope the extension will see it.”

There was also a separate JavaScript error. The onboarding catch blocks tried another native status request immediately after a permission or picker failure. When that second request rejected, it escaped as an uncaught promise. Removing those implicit retries let the original error appear and guaranteed busy state cleared. That correction could ship through JavaScript; the native storage correction needed an updated installed client.

Diagnostics finally let us stop guessing

“The app did not open” could mean routing, eligibility, storage, monitor registration, a timeout, another restriction, or visible shield behavior. We added a persistent timeline across the host and extensions, with process/run IDs, session IDs, timestamps, SDK error domains and codes, and the important stage transitions.

Observed evidenceWhat to investigate
grant_ineligible before a session existsAuthorization receipt, selection, task/demo state, or a real required lock.
monitor_failedThe SDK's actual error, including capacity or registration rejection.
Successful system approval, rejected receiptThe persistence path that saves the authorization receipt.
Accepted grant, settings write returned, shield still visibleOther stores, current lock inputs, and the observed OS presentation.
Expiry callback recorded, reconciliation failedState, lock contention, or enforcement writes after delivery.
Expiry repaired only after opening the hostWhether autonomous delivery/enforcement worked before that repair.

The exported report omits app tokens and names, task text and identifiers, websites, and usage history. Logging is bounded and best effort. A missing event can mean a process died before flushing its journal; it does not automatically prove Apple never called the extension.

The most useful testing rule was to observe the result before returning to Due or Die. Opening the host legitimately refreshes authorization and reconciles deadlines. That can repair the exact failure you are trying to inspect. The diagnostic export itself is read-only, but getting back into the app can already have changed the situation.

What ultimately worked

The working flow came from fixing the whole chain: explicit eligibility, persisted deadlines, future monitor registration, bounded grant handling, host-confirmed authorization, and a critical-state save that could report its own failure correctly. The final storage correction addressed the rejected authorization receipt, but it sat on top of the earlier scheduling and authorization repairs. A single API call was never going to repair every failure.

For anyone building the same interruption, I would start by recording exactly where a choice stops: before eligibility, before persistence, during registration, during shield mutation, or after the app should have reopened. Then test expiry without letting the host quietly repair it. Those observations were what finally turned this from “Screen Time is acting weird” into bugs I could actually fix.