A batch photo export looks finished in your head the moment the user taps Export. On the device, it has only just started. Eighty large photos still have to be rendered and written out, and the person who tapped the button will almost certainly leave the app — to answer a message, to check the result in Photos, or just because waiting feels unproductive.
When they leave, iOS does not owe you the rest of the job. You get a short grace period if you ask for it, and then the process can be suspended. If you do nothing, the batch stops wherever it was. If you ignore the expiration warning, the work can disappear mid-file. If you restart from photo 1 the next time the app opens, you may write a second copy of the photos that already made it out.
I build BatchMark, an iPhone app for finishing photos in batches, so this is a problem I have to take seriously. What follows is a teaching version of the pattern I'd recommend: a background task for the grace period, an expiration handler that stops cleanly, and a checkpoint file so a later launch can continue. It is not the app's source.
1. Ask for a grace period, not for a miracle
For work the user just started in the foreground, the tool you want first is UIApplication.beginBackgroundTask(withName:expirationHandler:).
It does one thing. It tells the system: I have a job open, please give me a little time after the app leaves the foreground to wrap it up. The amount of time is not documented as a number you can bank on, and it is not a way to run for minutes in the background on demand. Treat it as a short window whose only job is to let you finish the current photo, write down where you got to, and end the task.
Longer, deferrable work belongs to BGTaskScheduler and a processing task, which runs when the system feels like it — often overnight, and never as a promise that an export the user is waiting on will continue. That is a different design. This post stays with the "they just left, finish or checkpoint now" case.
Start the background task before you kick off the work, and end it exactly once when you are done or when you are told to stop.
import UIKit
@MainActor
final class BatchExportRunner {
private var backgroundTask: UIBackgroundTaskIdentifier = .invalid
private let checkpointURL: URL
private let stop = RequestedStop()
init(checkpointURL: URL) {
self.checkpointURL = checkpointURL
}
func start(photos: [URL]) {
beginBackground()
let urls = photos
Task.detached { [checkpointURL, stop] in
let worker = BatchWorker(checkpointURL: checkpointURL, stop: stop)
await worker.run(photos: urls)
await MainActor.run { self.endBackground() }
}
}
private func beginBackground() {
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "batch-export") { [weak self] in
self?.handleExpiration()
}
if backgroundTask == .invalid {
// The system refused. Run as far as you can in the foreground, and
// still write a checkpoint if the user leaves.
}
}
private func handleExpiration() {
stop.cancel()
// Do not start a new photo here. The handler is for stopping and
// handing the task back, not for more rendering.
endBackground()
}
private func endBackground() {
guard backgroundTask != .invalid else { return }
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
}
final class RequestedStop: @unchecked Sendable {
private let lock = NSLock()
private var cancelled = false
func cancel() {
lock.lock(); cancelled = true; lock.unlock()
}
var isCancelled: Bool {
lock.lock(); defer { lock.unlock() }
return cancelled
}
}
Two details are easy to get wrong.
End the task. Every beginBackgroundTask needs a matching endBackgroundTask. If you forget, the system does not reward you with more time. It may start treating the app as a bad citizen and cut you off sooner next time.
The expiration handler is not a second workplace. By the time it runs, your remaining time is already almost gone. Set a flag, make sure the loop will not start another photo, and end the task. The checkpoint should already have been written after the last successful photo, or be written in a hurry from the worker when it sees the flag. Don't start encoding photo 61 in the handler.
2. Write a checkpoint after every successful photo
A checkpoint is a small file that answers two questions: which photos already exported, and which one should run next. I use a JSON file in the app's caches or application-support directory, keyed by a job id so a new batch doesn't inherit an old one.
import Foundation
struct Checkpoint: Codable, Equatable {
var jobID: String
var completedIDs: [String]
var outputDirectory: String
}
struct BatchWorker {
let checkpointURL: URL
let stop: RequestedStop
func run(photos: [URL]) async {
var checkpoint = (try? load()) ?? Checkpoint(
jobID: UUID().uuidString,
completedIDs: [],
outputDirectory: newOutputDirectory().path
)
let done = Set(checkpoint.completedIDs)
for url in photos {
if stop.isCancelled { break }
let id = url.lastPathComponent
if done.contains(id) { continue }
do {
try await exportOne(url, to: checkpoint.outputDirectory)
checkpoint.completedIDs.append(id)
try save(checkpoint)
} catch {
// Record the failure if you want, but don't mark it completed.
// Then keep going, or stop, depending on the error.
continue
}
}
}
func load() throws -> Checkpoint {
let data = try Data(contentsOf: checkpointURL)
return try JSONDecoder().decode(Checkpoint.self, from: data)
}
func save(_ checkpoint: Checkpoint) throws {
let data = try JSONEncoder().encode(checkpoint)
try data.write(to: checkpointURL, options: .atomic)
}
}
Atomic writes matter here. A checkpoint that is half-written is worse than an old one: you can lose the list of completed photos and redo work, or worse, skip something you shouldn't. Data.write(to:options: .atomic) writes to a temporary file and replaces the destination.
I use the photo's existing filename as the id only because this teaching example starts from files on disk. If your batch comes from PhotoKit local identifiers, store those instead. Don't use the index in the array as the only key — the list can change if the user edits the selection.
The completed list is also what stops duplicates. If photo 1 through 40 made it out, and the app is killed before 41, the next launch should skip 1–40 and start at 41, writing into the same output directory. That is why the checkpoint stores the output path, not just the ids.
3. Resume on the next launch, and tell the user
When the app becomes active again, look for an unfinished checkpoint before you offer a blank export screen as if nothing happened.
func unfinishedJob() -> Checkpoint? {
guard let checkpoint = try? BatchWorker(
checkpointURL: checkpointURL,
stop: RequestedStop()
).load() else { return nil }
return checkpoint.completedIDs.isEmpty ? nil : checkpoint
}
If a job is unfinished, offer to continue it. Don't silently start it again in the background — the user may have cancelled on purpose, or they may have changed the watermark. A simple "Continue last export? 40 of 80 were saved." is enough. If they dismiss it, delete the checkpoint so you don't ask forever.
If they continue, reuse the same output directory and the same completed list. If they start a new batch, write a new job id so the old completed list cannot leak into the new run.
4. What I would not do
- Guess how many seconds you have left and try to race the whole remainder. You don't know, and the last photo may be the largest one. Finish the current photo only if it will complete quickly; otherwise abandon it and leave it off the completed list.
- Do UI work in the expiration handler. Update the flag and get out. Refresh the progress UI the next time you are in the foreground.
-
Rely on
UIApplication.shared.backgroundTimeRemainingas a scheduler. It is a hint, and it can drop quickly. I would rather checkpoint often than try to be clever with the remaining clock. - Leave temporary render files behind as the only record of progress. Temp files are useful, but a single JSON checkpoint is what you can load without scanning a directory and guessing which files are complete.
A short checklist
- Call
beginBackgroundTaskbefore the loop, on the main actor. - After each successful photo, append its id and atomically write the checkpoint.
- In the expiration handler, set a cancel flag and end the task. Do not start more work.
- In the loop, check the flag before each photo. A photo that didn't finish is not completed.
- End the background task when the loop finishes, even if some photos failed.
- On the next foreground, offer to resume from the checkpoint, into the same output folder.
None of this makes a 80-photo export "a background app." It just means that leaving the app mid-way is a situation you planned for, instead of a hole the user falls into. The grace period is short. The checkpoint is what makes the short period enough.
Top comments (0)