Make File Imports Survive Security Scoped URL Access
A file importer returns a URL, the UI dismisses, and a parser starts a moment later. Sometimes the parser succeeds. Sometimes the same code reports that the file cannot be opened.
A URL identifies a resource. It does not, by itself, describe how long your app can access that resource or whether another process needs to prepare it first.
For an import feature, a useful boundary is to copy the selected file into app-owned storage before handing it to the rest of the pipeline. The parser then works with your copy instead of depending on the picker’s access lifetime.
Keep access around the actual operation
SwiftUI’s fileImporter documentation calls out security-scoped access for the returned URL. Apple’s URL documentation also requires balancing a successful start with a stop when the work finishes.
A common mistake is starting access in the picker callback, launching a task, and immediately stopping access when the callback returns. The task may not have read anything yet. Put the lifetime inside the operation that actually uses the file.
Here is a synchronous worker for a single regular file:
import Foundation
enum ImportFailure: Error { case notRegularFile, coordinationProducedNoResult }
func copyRegularFile(from source: URL, to destination: URL) throws {
let values = try source.resourceValues(forKeys: [.isRegularFileKey])
guard values.isRegularFile == true else { throw ImportFailure.notRegularFile }
try FileManager.default.copyItem(at: source, to: destination)
}
func importCopy(from selectedURL: URL, into importsDirectory: URL) throws -> URL {
let didStart = selectedURL.startAccessingSecurityScopedResource()
defer {
if didStart { selectedURL.stopAccessingSecurityScopedResource() }
}
let files = FileManager.default
let folder = importsDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
try files.createDirectory(at: folder, withIntermediateDirectories: true)
var accepted = false
defer { if !accepted { try? files.removeItem(at: folder) } }
let destination = folder.appendingPathComponent("source.bin")
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinationError: NSError?
var copied: Result<URL, any Error>?
coordinator.coordinate(readingItemAt: selectedURL, options: [], error: &coordinationError) {
readableURL in
copied = Result {
try copyRegularFile(from: readableURL, to: destination)
return destination
}
}
if let coordinationError { throw coordinationError }
guard let copied else { throw ImportFailure.coordinationProducedNoResult }
let result = try copied.get()
accepted = true
return result
}
This helper is for importing a copy, not editing the original in place. It generates a private destination name, rejects directories, and removes its own incomplete import folder on failure. Keep the original filename separately if the UI needs it.
A false return from startAccessingSecurityScopedResource() is not treated as proof that every possible input URL is unreadable. An app-owned URL may not need a security scope. The copy still has to succeed through normal filesystem access; the helper never bypasses a permission error.
Use the coordinator’s URL
The coordinator’s accessor supplies readableURL. Use that value instead of reaching back to selectedURL. Apple’s coordinated-read reference explicitly allows the accessor URL to differ from the original.
There are two error paths. Coordination can fail before the accessor runs, and the file operation inside the accessor can fail. Capturing both avoids accidentally returning a destination that was never populated.
This coordination API blocks its calling thread. Run the worker on your import operation queue, with progress and cancellation owned by the feature. Calling it inside a Task created by a main-actor view does not automatically make synchronous work leave the main actor. Large or remote-provider files need a deliberate execution context.
Decide whether you want a copy or a continuing relationship
An import copy is useful for an attachment, a CSV ingestion job, or a document that becomes part of your app’s own library. It costs storage and stops following later edits to the original. Make that behavior clear in the product.
An editor that promises to modify the picked document has a different responsibility. Use the document architecture appropriate to that feature, including ongoing coordination and the platform’s bookmark/access rules. Do not quietly turn an “Open” operation into an import just to simplify permissions. Our WritableDocument article covers a document-based app shape.
The example rejects folders but does not validate your file format or impose a byte limit. Those are separate import rules. Validate before adding the copied file to the user’s library, and remove rejected copies through the same owner that created them.
Test with a provider, not just a local fixture
A local test can confirm that the copied bytes remain available after the source is removed and that a directory is rejected. It cannot prove that a file provider will download a placeholder, grant access, or recover from going offline.
Exercise the actual picker with an iCloud-only file, a third-party provider, a cancelled selection, and a provider that becomes unavailable. Keep permission/provider errors distinct from “unsupported file format” so the user gets an actionable explanation.
September 2026 review: the full helper compiles with Swift 6.4. Local copy and regular-file rejection checks passed. The published coordinated import also ran successfully on a temporary local file outside the sandbox, and its owned copy survived source removal. External file-provider permissions, downloads, and device behavior still need app testing.
The ownership boundary makes later code much easier to reason about: once import succeeds, the rest of the feature receives a file the app owns, not a promise that an earlier callback’s access is still alive.