A few weeks after shipping a background refresh feature, I opened Crashlytics one morning and found the non-fatal list filled with BGTaskSchedulerErrorDomain Code=1. Nothing had crashed, so nothing had alerted me. The widget had been showing stale content for days, and nobody had said a word.
My first instinct was the Info.plist. I checked the identifier spelling three times. It was correct, and I ran out of ideas. It was only when I went back to Apple's documentation that I noticed a missing Info.plist entry does not produce Code=1 at all — it produces Code=3. I had started searching without ever questioning the number.
The one thing I'd like you to take from this piece: the error code already tells you half of where to look. I'm assuming a Rork-generated Expo (React Native) app with BGTaskScheduler added afterwards. Below I read Code=1, 2, and 3 the way Apple defines them, then work through the causes in the order I now check them.
Code=1 and Code=3 point at different places
Errors thrown by BGTaskScheduler.submit(_:) live in BGTaskSchedulerErrorDomain, and Apple documents the causes under BGTaskScheduler.Error.Code (checked against the official documentation, November 2026).
| code | name | causes Apple lists | who fixes it |
|---|---|---|---|
| 1 | unavailable | The person turned off Background App Refresh / the app runs on Simulator / an extension is trying to schedule work | Mostly the device. Submitting from an extension is yours to fix |
| 2 | tooManyPendingTaskRequests | Too many pending requests of that type (1 refresh task and 10 processing tasks in total) | You |
| 3 | notPermitted | A required mode is missing from UIBackgroundModes / the identifier is not in BGTaskSchedulerPermittedIdentifiers | You (Info.plist) |
| — | immediateRunIneligible | A request asked to run immediately and system conditions prevented it | Only relevant to the newer task types |
The short version: Code=1 means "this environment can't schedule it," Code=3 means "this app isn't allowed to schedule it." Most Code=1 reports come from user settings and will not go away however many times you reread your code. Code=3, on the other hand, is almost always a configuration mistake on our side.
I left the number for immediateRunIneligible blank because I haven't been able to confirm its raw value in the official docs. If your app only uses BGAppRefreshTaskRequest and BGProcessingTaskRequest, the three you will see are 1, 2, and 3.
Make the submit failure log readable first
Triage by code only works if the device state arrives alongside the code. Wrapping submit like this means a glance at Crashlytics is enough to tell which pile a report belongs to.
// BackgroundRefresh.swift (main app target)
import BackgroundTasks
import UIKit
import os
enum BackgroundTaskID {
static let appRefresh = "net.rorklab.app.refresh"
}
private let log = Logger(subsystem: "net.rorklab.app", category: "bgtask")
func refreshStatusLabel() -> String {
switch UIApplication.shared.backgroundRefreshStatus {
case .available: return "available"
case .denied: return "denied" // turned off in Settings
case .restricted: return "restricted" // e.g. limited by a management profile
@unknown default: return "unknown"
}
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: BackgroundTaskID.appRefresh)
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
do {
try BGTaskScheduler.shared.submit(request)
log.info("bgtask submitted id=\(request.identifier, privacy: .public)")
} catch let error as NSError {
let status = refreshStatusLabel()
log.error("bgtask submit failed code=\(error.code) status=\(status, privacy: .public)")
// If you use Crashlytics, send code and status together as custom keys
// Crashlytics.crashlytics().setCustomValue(status, forKey: "bg_refresh_status")
// Crashlytics.crashlytics().record(error: error)
}
}The point of sending backgroundRefreshStatus is to split the Code=1 pile into "people who turned it off" and "everything else." UIApplication.shared belongs on the main thread, so call scheduleAppRefresh() while the app is still in the foreground — just before sceneDidEnterBackground, for instance.
I used to send only code, throwing away both userInfo and the status. When Code=1 spiked, the only way to find out why was to ask users for screenshots of their Settings screen. If you send a number, send what you need to read it — that's the line I hold now.
Split the collected logs by code and state
If you can export a CSV from Crashlytics' BigQuery export or your own log pipeline, this script shows the shape of the piles right away. It expects five columns, build,os,code,refresh_status,target, where target is the target that emitted the log (app or the extension name).
#!/usr/bin/env python3
"""Tally BGTaskScheduler submit failures exported from Crashlytics or similar,
and print where to look for each code. Columns: build,os,code,refresh_status,target"""
import csv, sys
from collections import Counter, defaultdict
HINT = {
"1": "unavailable: Background App Refresh setting / Simulator / submit from an extension",
"2": "tooManyPendingTaskRequests: 1 refresh and 10 processing requests at most",
"3": "notPermitted: BGTaskSchedulerPermittedIdentifiers and UIBackgroundModes in Info.plist",
}
def main(path):
rows = list(csv.DictReader(open(path, newline="", encoding="utf-8")))
by_code = Counter(r["code"] for r in rows)
print(f"total={len(rows)}")
for code, n in by_code.most_common():
print(f" code={code} n={n} -> {HINT.get(code, 'unknown code (check your SDK version)')}")
# Split code=1 by refresh_status and target
c1 = [r for r in rows if r["code"] == "1"]
status = Counter(r["refresh_status"] for r in c1)
target = Counter(r["target"] for r in c1)
print("code=1 by refresh_status:", dict(status))
print("code=1 by target:", dict(target))
off = status.get("denied", 0) + status.get("restricted", 0)
if c1 and off == len(c1):
print("verdict: every code=1 is a device setting. Revisit how you explain it, not the code")
elif c1:
rest = len(c1) - off
print(f"verdict: {rest} code=1 rows have refresh_status=available. "
"Check for submits from an extension target, or Simulator logs mixed in")
# Did code=3 start with a particular build? (suspect a prebuild overwrite)
per_build = defaultdict(Counter)
for r in rows:
per_build[r["build"]][r["code"]] += 1
for b in sorted(per_build):
print(f" build={b} {dict(per_build[b])}")
first3 = next((b for b in sorted(per_build) if per_build[b]["3"]), None)
if first3:
print(f"verdict: code=3 starts at build={first3}. Diff Info.plist around that prebuild")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "bgtask_errors.csv")To check it runs, I fed it an eight-row CSV made up for this explanation (these are not numbers from a real app), using Python 3.10:
$ python3 bgtask_triage_en.py bgtask_errors.csv
total=8
code=1 n=5 -> unavailable: Background App Refresh setting / Simulator / submit from an extension
code=3 n=3 -> notPermitted: BGTaskSchedulerPermittedIdentifiers and UIBackgroundModes in Info.plist
code=1 by refresh_status: {'denied': 3, 'restricted': 1, 'available': 1}
code=1 by target: {'app': 4, 'widget': 1}
verdict: 1 code=1 rows have refresh_status=available. Check for submits from an extension target, or Simulator logs mixed in
build=41 {'1': 3}
build=42 {'1': 2, '3': 3}
verdict: code=3 starts at build=42. Diff Info.plist around that prebuildReading it is simple. Code=1 rows marked denied or restricted are user settings and not fixable from the app. The rows worth your time are Code=1 with available, and Code=3 that suddenly appears from a specific build. Builds are sorted as strings here; if your build numbers change digit count, sort with int().
Code=1, cause 1: Background App Refresh is off
If it only happens on real devices and clusters around certain users, this is nearly always it. When Settings > General > Background App Refresh is off globally or just for your app, submit returns Code=1. Low Power Mode also pauses background refresh, though I haven't found official wording on which code submit returns in that state.
You can't change the setting from the app, so the fix is in how you tell people:
- Read
backgroundRefreshStatusthe moment someone starts using the feature, and explain once, only when it is.denied. - Leave
.restrictedalone apart from logging it; it may come from a management profile the person can't change either. - Keep the message to one sentence that says why and where: "To fetch new content while the app is closed, Background App Refresh needs to be on for this app in Settings."
When I split my own Code=1 pile by backgroundRefreshStatus, most of it was denied. Once I knew that pile was not mine to fix, I stopped chasing it and spent the time on the small pile that was. It felt like setting something heavy down.
Code=1, cause 2: you're running on Simulator
The Background Tasks API isn't available on Simulator; it only works on physical devices. Expo's expo-background-task documentation says the same. Code=1 on Simulator is just the API failing correctly, so there's nothing to chase.
A common misunderstanding is that you can force-launch tasks from LLDB to test on Simulator. Apple's "Starting and Terminating Tasks During Development" says the debug functions such as _simulateLaunchForTaskWithIdentifier work only on devices. The steps look like this:
1. Set a breakpoint on the line right after a successful submit(_:)
2. Run the app on a device until it pauses at the breakpoint
3. Run the following in the debugger, then resume; the launch handler is called
(lldb) e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"net.rorklab.app.refresh"]These are private functions, so keep them to development. Apple warns that referencing them in a build submitted to the App Store is grounds for rejection.
If your tasks are defined in JS through Expo, BackgroundTask.triggerTaskWorkerForTestingAsync() lets you trigger them. It also only works in debug builds, not in production.
Code=1, cause 3: you're submitting from an extension
Wanting the widget to refresh itself, you put submit inside the widget extension target — another classic Code=1. Apple's description of unavailable includes an extension trying to schedule work (with keyboard extensions as a special case tied to Open Access).
Split the roles like this: the main app's background task fetches the data, and WidgetKit's timeline redraws it.
// Runs in the main app; tells the widget once the data is written
import BackgroundTasks
import WidgetKit
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleAppRefresh() // book the next run first
let work = Task {
await syncLatestData() // write into the App Group container
WidgetCenter.shared.reloadAllTimelines()
task.setTaskCompleted(success: true)
}
task.expirationHandler = {
work.cancel() // out of time: stop and report completion
task.setTaskCompleted(success: false)
}
}Depending on the extension type and OS version, submit may actually succeed and the problem shows up instead as "scheduled, but never runs." I wrote that path up in Your Widget Extension Can Submit a BGTaskScheduler Request. It Just Cannot Register the Handler. Either way, it resolves once you go back to fetch in the main app, display in the extension.
Code=3 means Info.plist, including Expo's identifier
Officially, Code=3 (notPermitted) has exactly two causes: a required mode is missing from UIBackgroundModes (fetch for refresh, processing for processing), or the submitted identifier is not literally present in BGTaskSchedulerPermittedIdentifiers.
Rork generates Expo apps, and if you use expo-background-task there's a Rork-specific trap here. The identifier the module schedules internally isn't one you chose; it's com.expo.modules.backgroundtask.processing. With CNG (Continuous Native Generation), prebuild adds that identifier and the processing background mode for you.
The trouble starts when you add your own native task and write the arrays yourself under ios.infoPlist. If you use both, list both.
{
"expo": {
"plugins": ["expo-background-task"],
"ios": {
"infoPlist": {
"UIBackgroundModes": ["fetch", "processing"],
"BGTaskSchedulerPermittedIdentifiers": [
"com.expo.modules.backgroundtask.processing",
"net.rorklab.app.refresh"
]
}
}
}
}For a while the Expo identifier wasn't documented, which was reported in expo/expo Issue #40440. That issue is now closed, and as of November 2026 the SDK 58 documentation spells out both required settings.
To confirm the values actually made it into the build, check the generated Info.plist after prebuild:
npx expo prebuild --platform ios
/usr/libexec/PlistBuddy -c "Print :BGTaskSchedulerPermittedIdentifiers" ios/*/Info.plist
/usr/libexec/PlistBuddy -c "Print :UIBackgroundModes" ios/*/Info.plistIf Code=3 started climbing on a particular day, the fastest route is to diff those arrays around that prebuild. I keep the inventory steps for what prebuild changes in Find the native edits expo prebuild will erase before you upgrade to SDK 57.
Code=2 means you've booked too many
According to the submit(_:) documentation, you can have 1 refresh task and 10 processing tasks scheduled in total; beyond that you get Code=2. Submitting again with the same identifier as a pending request simply replaces the old one without an error.
When Code=2 appears, it's nearly always because the identifier changes every time — a date or counter baked into it. Keep the identifier a fixed constant; you normally don't need to call cancel(taskRequestWithIdentifier:) before rescheduling.
When there's no error but nothing runs
If submit succeeds but the handler is never called, the problem lives outside the error codes. Apple documents two constraints:
- Every identifier in
BGTaskSchedulerPermittedIdentifiersneeds a handler, andregistermust finish before the app finishes launching (application(_:didFinishLaunchingWithOptions:)). - Registering the same identifier twice causes the system to kill the app.
Hand-editing Rork's generated code is an easy way to let the register and submit strings drift apart. I once missed app.refresh versus appRefresh and left a task that never ran for longer than I'd like to admit. Since then the identifiers live in an enum like BackgroundTaskID, and both calls reference it.
earliestBeginDate is a floor — "not before this" — not a way to make the task run sooner. Even with a time a few seconds away, the system picks the actual moment based on battery, network, and usage patterns. I use fifteen minutes as a habit, but that's a value that was easy to work with on my side, not something Apple specifies.
Confirm the request is still pending with getPendingTaskRequests
submit not throwing and iOS keeping your request are two different things. You can read back what iOS is holding with getPendingTaskRequests.
func dumpPendingTasks() {
BGTaskScheduler.shared.getPendingTaskRequests { requests in
guard !requests.isEmpty else {
log.error("no pending bgtask requests")
return
}
for request in requests {
log.info("pending id=\(request.identifier, privacy: .public) earliest=\(String(describing: request.earliestBeginDate), privacy: .public)")
}
}
}On a device, send the app to the background once, bring it back, and call this. If the list is empty right after submit, the request never took and you're back at the code table. If it's there but never runs, look at when you register, at the identifier strings, and at how long the system is waiting based on how the person uses the app.
Triage table: from symptom back to cause
| symptom | likely cause | how to check | fix |
|---|---|---|---|
| Code=1 only on Simulator | Simulator isn't supported | Run the same build on a device | Test on a device with LLDB, or with triggerTaskWorkerForTestingAsync |
| Code=1 only for some real users | Background App Refresh is off | backgroundRefreshStatus in the log is denied | Explain once when the feature is first used |
Code=1 while status is available | Submitting from an extension | Check which target emitted the log | Move submit to the main app; keep the extension for display |
| Code=3 on every device | Missing identifier or mode | Print the post-prebuild Info.plist with PlistBuddy | Add the values to both arrays and rebuild |
| Swift task runs, JS task never does | Expo's identifier dropped from the array | Is com.expo.modules.backgroundtask.processing present? | List it next to your own identifier |
| Code=2 | Over the pending limit | Does the identifier change each time? | Make the identifier a fixed constant |
| No error, pending list not empty, never runs | Register timing or mismatched identifier | Is register inside launch? Do the strings match? | Use an enum; register before didFinishLaunching ends |
Common misunderstandings
"Code=1 means a missing Info.plist entry." By Apple's definition, a missing identifier or mode is Code=3 (notPermitted). Rereading Info.plist for a Code=1 usually leads nowhere.
"LLDB lets you test launches on Simulator." Apple states the debug functions work only on devices. Treat Code=1 on Simulator as the expected result.
"A shorter earliestBeginDate makes it run sooner." It's a lower bound; the system decides the actual time. Expo's minimumInterval works the same way, with a 15-minute minimum and a 12-hour default.
Where you'll likely get stuck next
Once requests stick and the handler fires, the next thing you meet is "it ran, then stopped halfway." Background time is short, and when it runs out your expirationHandler is called. I've seen reports that forgetting setTaskCompleted(success:) there makes later runs get pushed back, though I haven't found official wording that says so.
You can test expiration without waiting, too, using _simulateExpirationForTaskWithIdentifier in LLDB on a device. When you get to building the work itself to production standards, Keeping Rork Apps Fresh While Closed covers the design including Silent Push and Android's WorkManager.
I've also taken the long way around once, chasing Code=1 when the build had never actually reached TestFlight. If that's where you're stuck, see Your Rork App Is Stuck on "Processing" in App Store Connect.
For a first step, add backgroundRefreshStatus to your submit failure log and ship the next build with it. Just seeing the Code=1 pile split in two makes it far clearer which part is actually yours to chase.