skip to content

With FileManager on iOS, why does moveItem(at:to:) that installs a re-scanned PDF over the old one throw on every rescan, and how should the replacement be written?

level: seniorimportance: should knowfreq 40%

answer

  1. not the shell's mv
  2. what sits at the destination
  3. Cocoa error code 516
  4. a method that swaps without losing data
  5. a Data writing option that swaps too

basics

~10 s

FileManager's moveItem(at:to:) and copyItem(at:to:) never overwrite: when an item already exists at the destination they stop and throw CocoaError.fileWriteFileExists. Replace a file with replaceItemAt(_:withItemAt:), or write the bytes with Data.write(to:options: .atomic).

solid answer

~40 s

`moveItem(at:to:)` is not `mv`: Apple documents that when an item with the same name already exists at the destination, it stops and returns an error, which in Swift is a thrown `CocoaError` with code `fileWriteFileExists` (516). The first scan works because nothing is there yet; every rescan throws. Removing the old file first and then moving opens a window with no scan at all, and a failed move then loses it. The right tool is `replaceItemAt(_:withItemAt:backupItemName:options:)`, which replaces the original in a way Apple describes as ensuring no data loss; the staged file must be on the same volume, so I stage it in the folder from `url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor:create:)`. When the new content is bytes in memory, `data.write(to: url, options: .atomic)` does the swap for me.

code

swift · 16 lines
swift
import Foundation

func stagingURL(for destination: URL) throws -> URL {
    let dir = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask,
                                          appropriateFor: destination, create: true)
    return dir.appending(path: destination.lastPathComponent)
}

func install(staged: URL, at destination: URL) throws {
    let fm = FileManager.default
    if fm.fileExists(atPath: destination.path(percentEncoded: false)) {
        _ = try fm.replaceItemAt(destination, withItemAt: staged)  // consumes `staged`
    } else {
        try fm.moveItem(at: staged, to: destination)
    }
}

go deeper

for a junior

Recall that moveItem and copyItem throw when the destination already exists, and that Data.write with .atomic replaces a file safely.

for a middle

Explain the error code, why remove-then-move loses data, and the difference between no options, .atomic and .withoutOverwriting on a Data write.

for a senior

Diagnose the works-once bug from the 516 error, write a same-volume replaceItemAt install, and handle the race between an existence check and the move.

for a principal

Insist that one helper owns installing and replacing files, so swaps, staging folders and per-file flags are written once instead of per feature.

## What moveItem(at:to:) promises `FileManager.moveItem(at:to:)` moves a file or directory to a new URL, and the destination URL must include the item's new name. Its documentation is explicit about a collision: **if an item with the same name already exists at the destination, the method stops the move and returns an error**. `copyItem(at:to:)` behaves the same way. In Swift both are throwing methods, and the error is a `CocoaError` in `NSCocoaErrorDomain` with code `fileWriteFileExists` (516), wrapping the POSIX "File exists" error. That explains the bug report exactly: the first scan of a page succeeds because the destination is empty, and every rescan of the same page throws. A shell `mv` overwrites by default, which is where the wrong expectation usually comes from. ## Why remove-then-move is not the fix The tempting patch is `try? fm.removeItem(at: destination)` followed by `moveItem`. It works in a demo and has two real problems: 1. Between the two calls there is **no file at all**. A crash, a kill by the system or another reader in that window sees the scan as gone. 2. If the move then fails, for example because the staged file was cleaned up, the old scan has already been deleted. ## replaceItemAt for files already on disk `replaceItemAt(_:withItemAt:backupItemName:options:)` exists for this job. Apple's documentation describes it as replacing the item's contents "in a manner that ensures no data loss occurs": - **Same volume only.** The original and the new item must be on the same volume, or the call fails. Ask `url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: destination, create: true)` for a temporary folder on the destination's volume and stage the new file there. - **The new item is consumed.** It is moved into place, so it is no longer at its staging URL afterwards. - **It returns the resulting URL.** That URL can differ from the original when a new file-system object had to be created, so use the returned value. - **Metadata.** By default the original's creation date and permissions are kept on the new item; `.usingNewMetadataOnly` in `FileManager.ItemReplacementOptions` takes the new item's metadata instead. - **Optional backup.** `backupItemName` keeps a copy of the original beside it during the swap, removed on success unless you pass `.withoutDeletingBackupItem`. ## Data.write(.atomic) for bytes in memory When the new content is a `Data` value, there is nothing to stage by hand. `.atomic` writes to an auxiliary file and replaces the original when the write completes, so the destination holds either the old bytes or the new ones. Two related options: | Option | Behaviour when the file already exists | |---|---| | none | overwrites in place; a crash mid-write can leave a partial file | | `.atomic` | writes a separate file, then swaps it in | | `.withoutOverwriting` | fails with `fileWriteFileExists` | The SDK header notes that `.withoutOverwriting` cannot be combined with `.atomic`, because an atomic write is allowed to replace the original. ## Matching the error in code Because the collision has its own code, the install can try the cheap move first and fall back to the swap only when it is needed: ```swift do { try fm.moveItem(at: staged, to: destination) } catch CocoaError.fileWriteFileExists { _ = try fm.replaceItemAt(destination, withItemAt: staged) } ``` Any other error, such as a missing staging file or a full disk, propagates unchanged instead of being hidden behind a generic retry. ## The same collision elsewhere `createDirectory(at:withIntermediateDirectories:)` has the mirror image of this behaviour. With `true` it succeeds quietly when the folder exists; with `false` it throws `fileWriteFileExists` for an existing folder, and fails when a parent folder is missing. `removeItem(at:)` is the opposite case: it deletes a folder together with everything inside it, and it throws `fileNoSuchFile` when nothing is at the URL, so a clean-up step should match that code rather than wrap every removal in `try?`. ## Checklist for code that installs a file - Expect `moveItem` and `copyItem` to throw on an existing destination, and decide what that means for this file. - For a replacement, use `replaceItemAt` with a same-volume staging file, or an `.atomic` write. - Match `CocoaError.fileWriteFileExists` explicitly instead of treating every error the same. - Check per-file settings such as backup exclusion after a replacement; an `.atomic` write, for one, leaves a new file without the old flag.

  • Why must the staged file be on the same volume for replaceItemAt?
    The documentation states the method works only when both items are on the same volume and that passing items on different volumes results in an error. Asking `url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: destination, create: true)` returns a temporary folder chosen for the destination's volume, which is the documented way to satisfy the rule.
  • In the install function, another task creates the destination between fileExists and moveItem. What happens?
    The `moveItem` call throws `fileWriteFileExists` and the staged file stays where it was, so nothing is lost but the install fails. If the caller catches that code and retries through `replaceItemAt`, the race resolves itself; the existence check is a fast path, not a guarantee.

  • Expecting moveItem(at:to:) to overwrite an existing file the way mv does
  • Deleting the old scan first, then moving, leaving a window with no file
  • Combining .atomic with .withoutOverwriting in Data.write options
  • Assuming replaceItemAt leaves the staged file at its original URL
  • Treating every thrown move error alike instead of matching fileWriteFileExists