In a SwiftUI board that imports dropped photos through FileRepresentation, saved photo URLs later point to missing files; why, and how do you fix it?
answer
- who owns the received file
- valid only during one closure
- copy first, then store the copy
- original file or a system copy
- async throws closures
basics
~20 sFileRepresentation's importing closure gets a ReceivedTransferredFile whose file is only guaranteed to exist while that closure runs. Storing received.file keeps a URL that can dangle; copy the file into the app's own container inside the closure and keep the copy's URL.
solid answer
~40 sA `FileRepresentation` moves content as a file instead of in-memory `Data`, which suits large photos because the receiver loads them only when needed. Its `importing` closure receives a `ReceivedTransferredFile`, and Apple's documentation is explicit: the file at `received.file` is only guaranteed to exist within the importing closure; if you need it longer, make a copy there. Saving that URL into the model is therefore the bug. The fix is to copy the file into a folder you own, such as Application Support, with `FileManager.default.copyItem(at:to:)` and return a model pointing at the copy. `isOriginalFile` says whether you got the sender's file or a copy; senders opt in to sharing originals with `SentTransferredFile(_:allowAccessingOriginalFile:)`, whose default is `false`. The closures are `async throws`, so a failed copy fails the import instead of producing a broken model.
code
swift · 22 linesimport SwiftUI
import UniformTypeIdentifiers
struct BoardPhoto: Transferable {
let fileURL: URL
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(contentType: .jpeg) { photo in
SentTransferredFile(photo.fileURL)
} importing: { received in
// received.file is only guaranteed to exist inside this closure.
let folder = URL.applicationSupportDirectory
.appending(path: "Board", directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: folder,
withIntermediateDirectories: true)
let copy = folder.appending(path: UUID().uuidString + "-"
+ received.file.lastPathComponent)
try FileManager.default.copyItem(at: received.file, to: copy)
return BoardPhoto(fileURL: copy)
}
}
}go deeper
Recall that a received file belongs to the transfer, not to your app, so you keep a copy rather than the URL you were handed.
Explain SentTransferredFile and ReceivedTransferredFile, the default copy behavior, and why the importing closure is where the copy happens.
Diagnose the dangling-URL bug from its delayed symptom, fix it with a throwing copy into an owned directory, and keep export work off the main actor.
Decide where imported media lives, how it is named and cleaned up, and whether the app ever edits originals in place, since that shapes storage and privacy.
## Files instead of bytes **`FileRepresentation`** is the Core Transferable representation for content that travels as a file URL. Apple recommends it for types that involve a large amount of data, such as a lengthy video: passing data around as a file is efficient, and the receiver loads it into memory only if it needs to. Its initializers follow the same direction rules as the other representations: - `FileRepresentation(contentType:shouldAttemptToOpenInPlace:exporting:importing:)` works both ways. - `FileRepresentation(exportedContentType:shouldAllowToOpenInPlace:exporting:)` only exports. - `FileRepresentation(importedContentType:shouldAttemptToOpenInPlace:importing:)` only imports. Both closures are `@Sendable`, `async` and `throws`. ## The two file descriptions | Type | Side | What it carries | |---|---|---| | `SentTransferredFile` | Sender, returned from `exporting` | `file` URL and `allowAccessingOriginalFile`, default `false` | | `ReceivedTransferredFile` | Receiver, passed to `importing` | `file` URL and `isOriginalFile` | When `allowAccessingOriginalFile` is `false`, the receiver can only gain access to a copy of the file. `isOriginalFile` tells the receiver whether its URL points to the sender's original or to a copy. The open-in-place flags express the same intent from each side: `shouldAllowToOpenInPlace` on an exporter lets the receiver try to reach the original and edit it; `shouldAttemptToOpenInPlace` on an importer asks for that access, and otherwise the receiver works with a copy made by the system. ## Why the stored URLs break The documentation for the importing closure states the rule: **the file referred to by `received.file` is only guaranteed to exist within the `importing` closure**, and if you need the file to be around longer, you make a copy in that closure. A conformance written like this stores a URL with no guarantee behind it once the closure returns: ```swift } importing: { received in BoardPhoto(fileURL: received.file) // not guaranteed after return } ``` Because the guarantee ends quietly, the failure can surface later, when the board reloads, and it is easily mistaken for a caching or persistence bug. ## The fix 1. Choose a directory the app owns, such as `URL.applicationSupportDirectory` plus a subfolder, and create it if it is missing. 2. Build a unique destination name, for example a `UUID` string plus the received file's last path component. 3. Call `FileManager.default.copyItem(at: received.file, to: destination)` inside the closure. It throws, so a failed copy fails the import rather than producing a model that points nowhere. 4. Return the model with the **copy's** URL, and persist that. The importing closure is `async`, so it is allowed to take the time a large copy needs; this is the representation Apple points to for file operations. ## Exporting files correctly The sending side of the same type has choices too. `SentTransferredFile(photo.fileURL)` points at a file the app already owns; with the default `allowAccessingOriginalFile: false`, receivers work on a copy, so they cannot change the board's photo. Pass `true` only when a receiver is meant to edit the original; the export-only initializer's `shouldAllowToOpenInPlace` parameter expresses the same intent at the representation level. When the receiver writes the item to disk, `suggestedFileName(_:)` gives the file a meaningful name instead of a generated one. ## Related rules on the export side - Apple's `draggable(_:)` documentation warns that doing work on the main actor while exporting an item isn't supported and might cause a hang; keep exporting closures from dispatching to the main actor. - `ProxyRepresentation` closures should stay quick: Apple directs file operations, network requests and other lengthy work to `FileRepresentation` or `DataRepresentation`. - Describe the file precisely: a PDF is `UTType.pdf`, not `UTType.fileURL` or `UTType.content`, so apps that handle the type can accept it. - `withExportedFile(contentType:fileHandler:)`, a default `Transferable` method since iOS 18.2, has the mirror-image lifetime: it writes the item to a temporary file and removes it after the handler returns. ## Choosing the representation in the first place | Payload | Fits | |---|---| | A small thumbnail rendered in memory | `DataRepresentation` | | A full-resolution photo or a video on disk | `FileRepresentation` | | A caption or link for text receivers | `ProxyRepresentation` to `String` or `URL` |
- When would you set shouldAttemptToOpenInPlace to true on an importer?When the app should edit the sender's file rather than keep its own copy, as a document editor might. The flag asks for access to the original on disk; whether you get it also depends on the sender, and `received.isOriginalFile` tells you which you received. A board that stores its own photos leaves it `false` and copies.
- Why not import the photo with DataRepresentation instead?`DataRepresentation` hands you the whole image as `Data` in memory, which is fine for small payloads but wasteful for large photos or video. `FileRepresentation` passes a file URL, and Apple notes the receiver loads it only if needed; you still copy it, but you never hold the full bytes just to save them.
- The URL in ReceivedTransferredFile stays valid for the life of the app.
- SentTransferredFile gives the receiver the original file by default.
- File copying belongs in a ProxyRepresentation closure.
- Large media should travel as DataRepresentation so it stays in memory.
- An exporting closure can hop to the main actor to read view state.