Make A Share Extension Hand Work Back To Your App

A share extension receives a file URL, starts an async task, and dismisses. By the time the task tries to read that URL, the file is gone. The containing app cannot recover it because the only record of the import lived in the extension’s memory.

Make the handoff durable before completing the extension request. A shared inbox gives the main app something concrete to discover the next time it runs.

Copy inside the provider’s lifetime

Apple’s loadFileRepresentation documentation says the temporary file is deleted when the completion handler returns. Passing that URL into a Task and immediately returning is not a transfer of ownership.

Copy the file to an app-owned location while the callback still has access. In this example, each import gets a unique staging directory, a fixed payload filename, and a manifest:

import Foundation

struct SharedImport: Codable, Sendable {
    let version: Int
    let id: UUID
    let accountID: UUID
    let payloadName: String
}
enum ShareImportError: Error { case invalidFile, tooLarge }
func stageSharedFile(_ source: URL, inbox: URL, accountID: UUID) throws -> URL {
    let manager = FileManager.default
    let values = try source.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
    guard values.isRegularFile == true else { throw ShareImportError.invalidFile }
    guard let size = values.fileSize, size <= 20 * 1_024 * 1_024 else {
        throw ShareImportError.tooLarge
    }
    let id = UUID()
    let staging = inbox.appendingPathComponent(".staging", isDirectory: true)
        .appendingPathComponent(id.uuidString, isDirectory: true)
    let ready = inbox.appendingPathComponent(id.uuidString, isDirectory: true)
    try manager.createDirectory(at: staging, withIntermediateDirectories: true)
    defer { try? manager.removeItem(at: staging) }
    try manager.copyItem(at: source, to: staging.appendingPathComponent("payload.bin"))
    let manifest = SharedImport(
        version: 1, id: id, accountID: accountID, payloadName: "payload.bin")
    try JSONEncoder().encode(manifest).write(
        to: staging.appendingPathComponent("manifest.json"), options: .atomic)
    try manager.moveItem(at: staging, to: ready)
    return ready
}
func receiveSharedFile(
    from provider: NSItemProvider, typeIdentifier: String, inbox: URL, accountID: UUID,
    completion: @escaping @Sendable (Result<URL, any Error>) -> Void
) -> Progress {
    provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { url, error in
        do {
            if let error { throw error }
            guard let url else { throw ShareImportError.invalidFile }
            // Copy while the provider's temporary URL is still valid.
            let ready = try stageSharedFile(url, inbox: inbox, accountID: accountID)
            completion(.success(ready))
        } catch { completion(.failure(error)) }
    }
}

The callback returns only after the copy and publication finish. Its completion receives the owned directory, not the provider’s temporary URL. Move any UI updates from that callback onto the appropriate actor.

The size check is a simple admission check for the provider’s temporary regular file. It does not impose a hard streaming limit on a source that changes during copying. For larger or less predictable inputs, use a bounded copy strategy and verify the final size too.

Publish the payload and manifest together

Both targets need the same configured App Group. Obtain its container URL with FileManager, create an inbox beneath it, and handle a missing container as a configuration error.

The app scans only ready job directories, never .staging. The final same-container directory move is the publication boundary: readers should not discover a job before its payload and manifest exist.

This uses immutable per-job directories instead of several processes rewriting one shared manifest. It still needs a single consumer or a claim mechanism if several app scenes can process the inbox. Apple’s extension sharing guide describes shared-container access and the need to coordinate it.

Treat manifest fields as inputs when reading them. Accept known versions, validate the account, and require the fixed payload name. Do not let an arbitrary manifest path escape its job directory.

Completion means the handoff is safe

After staging succeeds, update the extension UI and complete its request using the supported extension context API. Do not start required CPU work after completion and assume the extension will remain alive; the system can terminate it.

The app imports ready jobs when it next has an execution opportunity, such as launch or foreground activation. This design does not depend on forcing the containing app to open from the share extension.

If the product requires a transfer to continue immediately, evaluate the supported background URLSession path separately. A persisted inbox alone does not promise when the app will run.

Make consumption retryable

Use the manifest ID as an import identity. If the app terminates after inserting the document but before deleting the inbox job, discovering that job again should find the existing import rather than create a duplicate.

Delete the ready directory only after the destination store confirms its durable import. Keep failed jobs available for a deliberate retry or removal action, and apply a cleanup policy to abandoned staging directories. Do not scavenge a staging directory that another live extension is still writing.

An account switch is also a boundary. A job saved for one account must not be silently imported into whichever account happens to be active later.

September 2026 review: the fixture proved the owned copy survives source removal, the manifest retains its account, and directories are rejected as payloads. The provider bridge type-checked for iOS 17. Real extension termination, entitlements, and cross-process consumption were not exercised.