DEV Community

Maxwell
Maxwell

Posted on

Don't Abort the Whole Batch: Per-Photo Errors, Temp Files, and Cancel-Safe Exports in Swift

A batch export that stops at the first bad photo is a frustrating kind of almost-done. Someone picked eighty pictures, the app processed forty, hit a file that wouldn't decode, and handed back nothing. Or worse: it left a half-written JPEG in Recents and no explanation of what happened.

I build BatchMark, an iPhone app for finishing photos in batches. When a set is being watermarked or filtered, the export has to finish the photos it can, skip the ones it can't, and leave the phone no messier than it was before. This post is a teaching extract of that job structure, not the app's source. The image processing itself is out of scope. What matters here is how you run the job.

The shape I keep coming back to has four parts:

  1. Treat each photo as its own unit of work, with its own result.
  2. Write to a temporary file first, and only move it when the write has finished.
  3. Keep going after a failure, and collect the errors.
  4. Honour cancellation between photos, and clean up anything you created.

1. A job is a list of outcomes, not a single Boolean

The first version most of us write looks like this: a function that takes an array of URLs, writes every file, and throws if anything goes wrong. The caller then has two states, success or failure, and in the failure case it often has nothing to show.

A batch is not a transaction. Photo 17 being corrupt should not erase photos 1 to 16, and it should not prevent photos 18 to 80 from being tried. So the job should return a summary, not a void:

import Foundation
import ImageIO
import UniformTypeIdentifiers

struct ExportItem: Identifiable {
    let id: UUID
    let sourceURL: URL
    /// A name the user will recognise in an error list, e.g. "IMG_2031.HEIC".
    let displayName: String
}

enum ItemStatus: Equatable {
    case succeeded
    case failed(String)
    case skippedCancelled
}

struct ExportSummary {
    var statuses: [(item: ExportItem, status: ItemStatus)] = []

    var succeeded: [ExportItem] { statuses.compactMap { $0.status == .succeeded ? $0.item : nil } }
    var failed: [(ExportItem, String)] {
        statuses.compactMap {
            if case .failed(let message) = $0.status { return ($0.item, message) }
            return nil
        }
    }
    var cancelledRemaining: Int {
        statuses.reduce(0) { $0 + ($1.status == .skippedCancelled ? 1 : 0) }
    }
}
Enter fullscreen mode Exit fullscreen mode

The UI can then say something honest: 76 exported, 3 failed, 1 not started because the export was cancelled. Failed items should be listed by displayName, not by index. "Photo 14 failed" is only useful if the user can still see the original order.

2. Write to a temporary file, then move

Never write the destination filename until the file is complete. A crash, a thrown error, or a cancellation in the middle of CGImageDestinationFinalize should not leave a truncated image in the user's folder.

The pattern is old and still the right one: write to a unique URL in FileManager.default.temporaryDirectory, then move. Delete the temporary file on every unsuccessful path. defer is the reliable way to do that, as long as you set a flag when the move has succeeded:

enum ExportError: LocalizedError {
    case couldNotRead
    case couldNotWrite
    case destinationExists

    var errorDescription: String? {
        switch self {
        case .couldNotRead:  return "This photo couldn't be read."
        case .couldNotWrite: return "Couldn't write the exported file."
        case .destinationExists: return "A file with this name already exists."
        }
    }
}

func exportOne(_ item: ExportItem, to folder: URL, process: (URL) throws -> CGImage) throws -> URL {
    let tempURL = FileManager.default.temporaryDirectory
        .appendingPathComponent(UUID().uuidString)
        .appendingPathExtension("jpg")
    var moved = false
    defer {
        if !moved {
            try? FileManager.default.removeItem(at: tempURL)
        }
    }

    let cgImage = try process(item.sourceURL)
    try writeJPEG(cgImage, to: tempURL, quality: 0.9)

    let destination = folder.appendingPathComponent(item.displayName)
        .deletingPathExtension()
        .appendingPathExtension("jpg")

    // Don't overwrite a file the user already has.
    if FileManager.default.fileExists(atPath: destination.path) {
        throw ExportError.destinationExists
    }

    try FileManager.default.moveItem(at: tempURL, to: destination)
    moved = true
    return destination
}

func writeJPEG(_ image: CGImage, to url: URL, quality: CGFloat) throws {
    guard let dest = CGImageDestinationCreateWithURL(
        url as CFURL,
        UTType.jpeg.identifier as CFString,
        1,
        nil
    ) else { throw ExportError.couldNotWrite }

    let options: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: quality]
    CGImageDestinationAddImage(dest, image, options as CFDictionary)
    guard CGImageDestinationFinalize(dest) else { throw ExportError.couldNotWrite }
}
Enter fullscreen mode Exit fullscreen mode

If the destination name might collide, you can append a suffix (IMG_2031-2.jpg) instead of throwing. What I wouldn't do is overwrite silently. The export should add files, not replace ones the user already kept.

process is a stand-in for whatever you actually do to the photo — draw a watermark, apply a filter, resize. Keep it a pure "URL in, CGImage out" step so the job loop doesn't care.

3. Keep going after a failure

The loop itself is deliberately plain. Serial work, one photo at a time, each one wrapped in autoreleasepool so ImageIO objects don't accumulate across the batch. Parallelism is a separate decision, and on a phone I would cap it very low, if I used it at all. Two full-size decodes at once is already a lot.

func runExport(_ items: [ExportItem], to folder: URL, process: (URL) throws -> CGImage) async -> ExportSummary {
    var summary = ExportSummary()

    for item in items {
        if Task.isCancelled {
            summary.statuses.append((item, .skippedCancelled))
            continue
        }

        let status: ItemStatus = await Task.detached(priority: .userInitiated) {
            do {
                try autoreleasepool {
                    _ = try exportOne(item, to: folder, process: process)
                }
                return .succeeded
            } catch {
                return .failed(error.localizedDescription)
            }
        }.value

        summary.statuses.append((item, status))
    }

    return summary
}
Enter fullscreen mode Exit fullscreen mode

Once cancelled, the loop doesn't start new photos, but it still records the remaining items as skippedCancelled so the summary adds up to the original count. That's a small thing, and it saves the UI from having to do the arithmetic.

Catch the error per photo. Translate it into a short message the user can read. A missing file, an unsupported format, and a full disk are different problems; if you know which one it was, say so.

4. Cancellation is a checkpoint, not a rollback

Check Task.isCancelled between photos, not in the middle of a write if you can help it. If a write has already started, let it finish or delete the temporary file; don't leave a partial JPEG behind.

The more important design choice is what happens to work already done. If 30 files have already been moved into the destination folder, those 30 should stay. Cancellation means "stop starting new work," not "undo the batch." Rolling back is surprising. People would rather have the 30 and a clear note that the rest didn't run.

If you need to offer an undo, make it a separate, explicit action ("Delete the 30 files this export just added"), not the default meaning of Cancel.

What I'd check before shipping

  • A batch of one, a batch of many, and a batch that includes a 0-byte file, a non-image, and a photo that decodes fine.
  • Cancel before the first photo, in the middle of the list, and after the last write has started.
  • A destination folder that already contains some of the intended filenames.
  • A disk-full path: the current photo should fail, the temporary file should be removed, and the rest of the batch should still be attempted (or stopped cleanly if the disk is genuinely full).
  • Backgrounding: if the system suspends you, treat expiration as cancellation and clean up temps. Don't assume an export that was in flight has finished.

You don't need a new export architecture for this. You need to stop thinking of a batch as one transaction, and start thinking of it as a list of small, reversible steps. The photos that can be finished should be finished. The ones that can't should be named. And the phone should look as if you meant it.

Top comments (0)