Why does a 50 MB iOS upload fail after screen lock?
Question
An iOS field app uploads a 50 MB (400 megabits) inspection video over a 4 Mbps cellular link (100 seconds total) using URLSession.shared.uploadTask(with:from:completionHandler:). The technician locks the screen 10 seconds in, and seconds later the upload fails as iOS suspends the app.
A teammate wraps the call in beginBackgroundTask, which still fails at ~30 seconds. Next, they switch to URLSessionConfiguration.background(withIdentifier:) while keeping the closure completion handler, and the app immediately throws a runtime exception.
- Compare
beginBackgroundTask, backgroundURLSession, andBGAppRefreshTask/BGProcessingTaskfor this upload. - Configure a background
URLSessioncorrectly so the50 MBtransfer finishes while the app is suspended or terminated.
Show hints (3)
- "CHECK TRANSFER DURATION"
With
90seconds left after screen lock, the~30-secondbeginBackgroundTaskgrace window cannot finish a50 MBupload at4 Mbps. - "DELEGATE TO NSURLSESSIOND"
Use
URLSessionConfiguration.background(withIdentifier:)so the systemnsurlsessionddaemon runs the transfer out-of-process, even after app suspension or termination. - "FOLLOW BACKGROUND RULES"
Background sessions forbid closure completion handlers and in-memory
Datauploads. UseuploadTask(with:fromFile:), a session delegate, andhandleEventsForBackgroundURLSession.
Show checked explanation
At 4 Mbps, 50 MB (400 megabits) needs 100 seconds, leaving 90 seconds after lock at 10 seconds, far beyond beginBackgroundTask's ~30-second window. Use URLSessionConfiguration.background(withIdentifier:) with a file-backed uploadTask(with:fromFile:), delegate callbacks (not closure handlers), and handleEventsForBackgroundURLSession so nsurlsessiond completes the upload out-of-process. Reserve BGAppRefreshTask and BGProcessingTask for opportunistic, system-scheduled work.
Transfer-duration math (50 MB at 4 Mbps = 100 s), beginBackgroundTask grace-window failure, nsurlsessiond out-of-process upload handoff, and background session validation rules were simulated on CPython 3.12.10 (no iOS SDK or Xcode installed locally); Foundation and BackgroundTasks APIs checked against official Apple documentation. Checked by an editor other than the author.
Walkthrough
When the screen locks, iOS transitions your app to Background and freezes it in Suspended, cutting off in-process URLSession.shared sockets. Choosing the right mechanism depends on whether the work is short cleanup, a network transfer, or deferrable maintenance.
| mechanism | typical window | runs while app suspended? | best fit |
|---|---|---|---|
beginBackgroundTask | ~30 s grace | no (delays suspension) | brief local flush or tiny commit |
background URLSession | system-managed transfer | yes (nsurlsessiond daemon) | large uploads and downloads |
BGAppRefreshTask | ~30 s opportunistic | no (system wakes app) | small periodic feed refresh |
BGProcessingTask | minutes (power/budgeted) | no (system wakes app) | deferrable indexing or cleanup |
Here 50 MB at 4 Mbps takes 100 seconds (90 seconds remaining after locking at 10 seconds). Neither beginBackgroundTask (~30 seconds) nor opportunistic BGAppRefreshTask / BGProcessingTask (which iOS may delay for hours until charging) fits an immediate user upload.
URLSessionConfiguration.background(withIdentifier:) hands the upload to the out-of-process nsurlsessiond daemon, which continues even if iOS suspends or terminates your app. A terminated process loses all in-memory closures and RAM buffers. Because of that, Foundation enforces two strict rules: use delegate callbacks (closure completion handlers throw an exception) and upload from a file on disk (uploadTask(with:fromFile:)).
@MainActor
final class Uploader: NSObject, URLSessionTaskDelegate {
static let id = "com.example.app.video-upload"
var bgDone: (() -> Void)?
lazy var session: URLSession = {
let cfg = URLSessionConfiguration.background(withIdentifier: Self.id)
cfg.isDiscretionary = false
cfg.sessionSendsLaunchEvents = true
return URLSession(configuration: cfg, delegate: self,
delegateQueue: nil)
}()
func upload(fileURL: URL, to req: URLRequest) {
session.uploadTask(with: req, fromFile: fileURL).resume()
}
nonisolated func urlSessionDidFinishEvents(
forBackgroundURLSession s: URLSession
) {
Task { @MainActor in self.bgDone?(); self.bgDone = nil }
}
}When all transfers finish, iOS wakes or relaunches your app. In UIKit, application(_:handleEventsForBackgroundURLSession:completionHandler:) passes a completionHandler; recreate the session with the same id, store that handler in bgDone, and invoke it on @MainActor once urlSessionDidFinishEvents(forBackgroundURLSession:) fires. In SwiftUI, .backgroundTask(.urlSession(id)) completes automatically when its async closure returns.
Common mistakes
- Passing a completion-handler closure or in-memory
Datato a backgroundURLSession. Foundation rejects closure tasks at runtime and requires file-backeduploadTask(with:fromFile:). - Setting
cfg.isDiscretionary = trueon a user-initiated upload started in the foreground, which lets iOS defer the transfer until Wi-Fi and charging. - Forgetting to store and call the system
completionHandlerinsideurlSessionDidFinishEvents(forBackgroundURLSession:), causing background wakeups to time out and get penalized. - Creating multiple
URLSessioninstances with the same background identifier simultaneously, which leads to undefined delegate delivery and missed completion events.
Follow-up questions
- "What happens if the user force-quits the app from the app switcher while a background URLSession upload is running?" iOS cancels active background
URLSessiontransfers when the user explicitly force-quits the app and does not relaunch it automatically. That differs from system memory termination while suspended, wherensurlsessiondfinishes the upload and relaunches your app to deliver events. - "When should you set isDiscretionary = true on a background URLSession?" Set
isDiscretionary = trueonly for non-urgent background transfers started when the app is not actively waiting, such as pre-fetching offline maps or uploading analytics logs. iOS then waits for power and optimal network conditions such as Wi-Fi. - "Why can BGProcessingTask fail to run for hours even when you set earliestBeginDate to 15 minutes from now?"
earliestBeginDateis a lower bound, not a guaranteed schedule. iOS throttlesBGAppRefreshTaskandBGProcessingTaskusing battery level, Low Power Mode, thermal state, and user engagement, andBGProcessingTaskoften waits until the device is locked and charging.
What a strong answer covers
Computes the 100-second transfer versus ~30-second beginBackgroundTask limit, selects URLSessionConfiguration.background(withIdentifier:) over BGAppRefreshTask / BGProcessingTask, enforces file-backed uploadTask(with:fromFile:) plus delegate callbacks, and wires handleEventsForBackgroundURLSession to urlSessionDidFinishEvents.
Open in interactive practice deck →