What are the key considerations when implementing background fetch in an iOS app?

Instruction: Explain a resource-efficient background content refresh using BGAppRefreshTask on iOS 13 or later, including scheduling limits, expiration and the legacy fetch API distinction.

Context: This question assesses the candidate's knowledge of iOS background execution modes, focusing on the implementation of background fetch in a resource-efficient manner.

Updated

Official answer

For short content refreshes on iOS 13 and later, use the BackgroundTasks framework's BGAppRefreshTask. Background refresh is an opportunity scheduled by the system, not a timer that guarantees a fixed interval or an up-to-date screen at every moment.

  1. Enable the relevant background capability, list the permitted task identifier in BGTaskSchedulerPermittedIdentifiers, and register the launch handler before the app finishes launching.
  2. Submit a BGAppRefreshTaskRequest. Its earliestBeginDate is a lower bound, not a promised start time. Handle submission errors and schedule a future request when appropriate.
  3. Perform a small, bounded refresh. Fetch only changed data when the API supports it, avoid unnecessary radio wakeups, and persist progress safely. The operation should tolerate cancellation or repeated execution.
  4. Set an expiration handler that cancels outstanding work and performs prompt cleanup. Coordinate the completion path so setTaskCompleted(success:) is called once with the actual outcome, including unsuccessful cancellation. Do not keep working after reporting completion.
  5. Refresh stale content when the app returns to the foreground too. The system or user settings may prevent a background opportunity; essential behavior cannot depend on receiving one on time.

The older application(_:performFetchWithCompletionHandler:) API is relevant to legacy code. Apple documents that adding BGTaskSchedulerPermittedIdentifiers disables that legacy fetch path and setMinimumBackgroundFetchInterval(_:); do not assume both schedulers independently remain active.

Test success, no-change responses, network failure, expiration during a request and relaunch after interrupted work. Inspect content freshness, transferred bytes, completion time and energy use on devices. A simulated launch helps test the handler, but does not prove the system will schedule real launches at the requested frequency.

Sources

Apple background refresh workflow; earliestBeginDate semantics; expiration handling.

Related Questions