download

Why does a 50 MB iOS upload fail after screen lock?

Mobile~10 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Compare beginBackgroundTask, background URLSession, and BGAppRefreshTask / BGProcessingTask for this upload.
  2. Configure a background URLSession correctly so the 50 MB transfer finishes while the app is suspended or terminated.
Show hints (3)
  1. "CHECK TRANSFER DURATION"

    With 90 seconds left after screen lock, the ~30-second beginBackgroundTask grace window cannot finish a 50 MB upload at 4 Mbps.

  2. "DELEGATE TO NSURLSESSIOND"

    Use URLSessionConfiguration.background(withIdentifier:) so the system nsurlsessiond daemon runs the transfer out-of-process, even after app suspension or termination.

  3. "FOLLOW BACKGROUND RULES"

    Background sessions forbid closure completion handlers and in-memory Data uploads. Use uploadTask(with:fromFile:), a session delegate, and handleEventsForBackgroundURLSession.

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.

mechanismtypical windowruns while app suspended?best fit
beginBackgroundTask~30 s graceno (delays suspension)brief local flush or tiny commit
background URLSessionsystem-managed transferyes (nsurlsessiond daemon)large uploads and downloads
BGAppRefreshTask~30 s opportunisticno (system wakes app)small periodic feed refresh
BGProcessingTaskminutes (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:)).

"SWIFT"
@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 Data to a background URLSession. Foundation rejects closure tasks at runtime and requires file-backed uploadTask(with:fromFile:).
  • Setting cfg.isDiscretionary = true on 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 completionHandler inside urlSessionDidFinishEvents(forBackgroundURLSession:), causing background wakeups to time out and get penalized.
  • Creating multiple URLSession instances 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 URLSession transfers when the user explicitly force-quits the app and does not relaunch it automatically. That differs from system memory termination while suspended, where nsurlsessiond finishes the upload and relaunches your app to deliver events.
  • "When should you set isDiscretionary = true on a background URLSession?" Set isDiscretionary = true only 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?" earliestBeginDate is a lower bound, not a guaranteed schedule. iOS throttles BGAppRefreshTask and BGProcessingTask using battery level, Low Power Mode, thermal state, and user engagement, and BGProcessingTask often 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 →

Original OfferVibe question. Downloading files in the background · URLSessionConfiguration · Using background tasks to update your app · BGProcessingTask · Extending your app's background execution time.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.