Resume Background Uploads After Your App Relaunches

The upload screen says “Sending” before the app leaves the foreground. After relaunch, it says “Waiting” and creates another upload. Meanwhile, the original transfer may still be running in the system’s background session.

The missing piece is usually identity. A background transfer can outlive the objects that created it, so an in-memory array of tasks cannot be the upload queue’s only record.

Our continued-processing post covers producing a file before handing it to URLSession. This post starts at that handoff and asks what the next app process needs to know.

Keep the job and the transport task separate

Give each user-requested upload a durable job ID. Store its account, source-file location, payload revision, destination, and business state before creating the transfer. The exact storage technology can be the one your app already uses.

The job ID represents “upload this attachment.” URLSession’s task identifier represents one transport task inside one session. A retry might create another transport task for the same job; it should not invent a new business operation.

Use a stable background session identifier when reconstructing the session. Apple’s background-transfer guide documents reassociation with the same identifier and the requirement for file-based background uploads. Supply a delegate, and retain the app-owned source file while your recovery policy still needs it.

Associate a task with the persisted job before starting it:

import Foundation

func prepareUpload(
    jobID: UUID,
    file: URL,
    request: URLRequest,
    session: URLSession
) -> URLSessionUploadTask {
    let task = session.uploadTask(with: request, fromFile: file)
    task.taskDescription = jobID.uuidString
    return task
}

The caller durably stores the session/task mapping, then calls resume(). taskDescription is a useful correlation label, not a replacement for that database record or an authorization check. Recover using the saved mapping when a label is absent.

Reconcile before creating more work

After rebuilding the session, inspect its existing tasks. Project transport objects into small values before applying business decisions:

struct TransferSnapshot: Sendable {
    let taskID: Int
    let jobID: UUID?
}

func transferSnapshots(in session: URLSession) async -> [TransferSnapshot] {
    await session.allTasks.map {
        TransferSnapshot(
            taskID: $0.taskIdentifier,
            jobID: $0.taskDescription.flatMap(UUID.init(uuidString:))
        )
    }
}

There are four useful outcomes. One task matches a pending job: reattach the UI and observe it. A job has no task: its outcome needs reconciliation. Several tasks claim one job: investigate the duplicate. A task has no recognized job: resolve ownership before taking action.

Here is a pure function that makes those cases explicit:

struct RecoveryPlan: Equatable {
    var attached: [UUID: Int] = [:]
    var unresolved: Set<UUID> = []
    var duplicateJobs: Set<UUID> = []
    var unknownTaskIDs: Set<Int> = []
}

func planRecovery(
    pendingJobIDs: Set<UUID>,
    tasks: [TransferSnapshot]
) -> RecoveryPlan {
    var plan = RecoveryPlan(unresolved: pendingJobIDs)
    for task in tasks {
        guard let jobID = task.jobID, pendingJobIDs.contains(jobID) else {
            plan.unknownTaskIDs.insert(task.taskID)
            continue
        }
        plan.unresolved.remove(jobID)
        if plan.duplicateJobs.contains(jobID) { continue }
        if plan.attached.updateValue(task.taskID, forKey: jobID) != nil {
            plan.attached[jobID] = nil
            plan.duplicateJobs.insert(jobID)
        }
    }
    return plan
}

Notice what the function returns: a plan. It does not automatically cancel unknown tasks or resubmit missing ones. Task enumeration and delegate delivery can race; apply the plan through the same serialized job owner that processes completions, and recheck current durable state before mutating it.

Missing does not mean never delivered

Suppose the server accepted a file, the transfer finished, and the app exited before saving its success record. On the next launch, a missing task cannot tell you whether that server write happened.

Resolve that ambiguity with the backend’s operation-status or deduplication contract. Reuse the job’s operation identity when the server supports that behavior. Our retry-policy post explains why adding a header by itself does not create idempotency.

There is also a smaller crash window between persisting the job and creating its transport task. Both windows produce a job without a current task, but only one may already have reached the server. A queue that represents an unresolved outcome can handle both without guessing.

Finish the event handoff after saving the result

In a UIKit lifecycle, keep the completion handler supplied to application(_:handleEventsForBackgroundURLSession:completionHandler:). Apple’s session-finished-events documentation identifies the callback that signals delivery of the queued events and requires calling the UIKit completion handler on the main thread.

If your delegate forwards work to an actor or database queue, track that work too. Delivery of the delegate callback does not mean your asynchronous persistence has finished. Save terminal job state and any server receipt before reporting the handoff complete. Then remove files according to the queue’s retention policy.

A nil transport error alone is not application success. Validate the HTTP response and whatever acknowledgment the endpoint promises. Handle repeated completion processing so it cannot decrement a counter twice or resurrect a finished job.

Test recovery as a feature

The pure planner can be exercised without waiting for iOS scheduling: one match, no match, three duplicate matches, an unknown task, and the same snapshot applied twice. Add integration tests around crash windows and account changes in the actual app.

On a device, distinguish system termination from the user force-quitting the app. Apple documents that force-quitting cancels background transfers and prevents automatic relaunch. Removing the app from the switcher is not a faithful simulation of every background lifecycle event.

September 2026 review: the snapshot adapter, upload preparation, and planner compile with Swift 6.4. Executable planner checks passed for matching, unresolved jobs, duplicate detection, unknown tasks, and repeatability. The example is a recovery component, not a complete persistent upload service; device relaunch behavior still needs integration testing.

The useful promise is modest: after relaunch, the app can explain what it knows, recover what it can prove, and avoid creating another write merely because its old view model disappeared.