Skip to main content
3Nsofts logo3Nsofts
Security & Compliance

Restore Sandboxed File Access with Security-Scoped Bookmarks

Save and restore a user-selected file in a sandboxed Mac app with stale bookmark refresh, balanced access, useful recovery and relaunch tests.

By Ehsan Azish · 3NSOFTS··7 min read

A sandboxed Mac app can remember a document's path and still lose access after relaunch. Persist a security-scoped bookmark from the user's selection, resolve it when needed, and hold access for the entire file operation.

This guide builds a small read-only “reopen my selected file” feature. It deliberately asks for one file. A folder picker grants a broader working scope and should be reserved for a feature that actually needs a folder.

Saved file URL compared with a security-scoped bookmark restored before a file read.

The card sketches the sequence. The complete example below starts access before refreshing stale data and balances that successful start even when saving or reading throws.

Contents

Choose a narrow capability

A file URL identifies a resource. The bookmark preserves information needed to resolve that selection and obtain security-scoped access later. Keep the bookmark data rather than reconstructing a URL from a saved path.

For this sandboxed macOS example, enable App Sandbox, user-selected read-only files, and app-scoped bookmarks. A write-capable editor would need an intentional read-write policy and corresponding picker entitlement. Document-scoped bookmarks have a different sharing and relative-resolution model. Do not substitute those for the app-scoped bookmark used here. Apple bookmark entitlements · Apple App Sandbox entitlement reference

<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<key>com.apple.security.files.bookmarks.app-scope</key>
<true/>

Persisting a bookmark does not override filesystem permissions, privacy controls, or availability of the underlying volume.

Save and restore access in Swift

The following complete example uses a storage protocol so the UI flow can be tested with an in-memory replacement. The UserDefaults implementation holds one small bookmark. Use your existing private application store for a document library with multiple entries.

It targets a native sandboxed macOS app. The example reads small files synchronously to make the access lifetime visible. Use a worker for large imports.

import AppKit

@MainActor
protocol BookmarkStore {
    func load() -> Data?
    func save(_ data: Data) throws
    func remove()
}

@MainActor
final class DefaultsBookmarkStore: BookmarkStore {
    private let defaults: UserDefaults
    private let key = "selectedDocumentBookmark"

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    func load() -> Data? { defaults.data(forKey: key) }
    func save(_ data: Data) throws {
        defaults.set(data, forKey: key)
    }
    func remove() { defaults.removeObject(forKey: key) }
}

@MainActor
final class SelectedDocument {
    enum AccessError: Error {
        case noSelection
        case scopeDenied
        case notAFile
    }

    private let store: any BookmarkStore

    init(store: any BookmarkStore) {
        self.store = store
    }

    // Returns nil when the user cancels.
    func selectAndRead() throws -> Data? {
        let panel = NSOpenPanel()
        panel.canChooseFiles = true
        panel.canChooseDirectories = false
        panel.allowsMultipleSelection = false
        guard panel.runModal() == .OK,
              let url = panel.url else { return nil }

        guard url.startAccessingSecurityScopedResource() else {
            throw AccessError.scopeDenied
        }
        defer { url.stopAccessingSecurityScopedResource() }

        let data = try readFile(url)
        try store.save(makeBookmark(url))
        return data
    }

    func restoreAndRead() throws -> Data {
        guard let bookmark = store.load() else {
            throw AccessError.noSelection
        }
        var stale = false
        let url = try URL(
            resolvingBookmarkData: bookmark,
            options: [.withSecurityScope, .withoutUI],
            relativeTo: nil,
            bookmarkDataIsStale: &stale
        )
        guard url.startAccessingSecurityScopedResource() else {
            throw AccessError.scopeDenied
        }
        defer { url.stopAccessingSecurityScopedResource() }

        let data = try readFile(url)
        if stale {
            try store.save(makeBookmark(url))
        }
        return data
    }

    func forget() { store.remove() }

    private func makeBookmark(_ url: URL) throws -> Data {
        try url.bookmarkData(
            options: [.withSecurityScope,
                      .securityScopeAllowOnlyReadAccess],
            includingResourceValuesForKeys: nil,
            relativeTo: nil
        )
    }

    private func readFile(_ url: URL) throws -> Data {
        let values = try url.resourceValues(
            forKeys: [.isRegularFileKey]
        )
        guard values.isRegularFile == true else {
            throw AccessError.notAFile
        }
        return try Data(contentsOf: url)
    }
}

Call SelectedDocument(store: DefaultsBookmarkStore()) from main-actor UI code and keep that controller as UI state. Catch errors at the action boundary. Show “Choose the file again” with a picker action instead of retrying in a tight loop. Cancellation should leave the existing selection intact.

The resolver reports whether the bookmark is stale. A stale result may still resolve successfully. This implementation reads under an active scope, then refreshes the stored bookmark. A failed refresh is surfaced and leaves the previous bookmark in storage. Apple bookmark resolution

Handle changes to the resource

Moved or renamed file. Bookmark resolution may locate it. Read the resolved URL rather than your old display path. Refresh stale data after successful access.

Deleted file. Resolution or reading can fail. Offer reselection and an explicit option to forget the saved entry.

Unmounted drive. The sample uses .withoutUI to avoid an unexpected resolver dialog. Ask the user to reconnect the drive and retry. Do not silently select a different file with the same name.

Changed permissions. A successful scope activation does not guarantee a successful read. Handle the actual operation's error as well.

These are separate states in the product. “Reconnect the drive” is more useful than “Permission denied” when the volume is absent, but only show a specific diagnosis when you have evidence for it.

Keep access alive for the operation

Every successful startAccessingSecurityScopedResource() needs a matching stop. Place the stop immediately in a defer so an error cannot skip it. Apple warns that unbalanced access can exhaust kernel resources. Apple starting security-scoped access

For an asynchronous import, acquire the scope in the worker that owns the job, keep it open until all child reads finish, and release it on completion or cancellation. Starting a task inside the synchronous function above would let the defer run before the task finishes.

Use file coordination where your document workflow requires coordination with other writers. A security scope grants access; it does not make the resource immutable or serialize changes by another app.

What can still go wrong

The store succeeds only in memory. Relaunch testing is necessary. A passing same-process read proves little about persistence.

A helper reads instead of the main app. Review that process's sandbox and bookmark handoff separately. Do not assume passing a URL string transfers the main app's authority.

The “forget” button overpromises. Removing your stored bookmark and stopping active accesses ends your app's retained use of this entry. It cannot revoke independently retained grants held elsewhere.

Logs leak filenames. Bookmark bytes, full URLs, document contents, and volume names can reveal private information. Log an operation ID and an error category. Ask for explicit consent before attaching diagnostic file metadata.

An arbitrary URL is passed in. This helper intentionally fails closed when scope activation returns false. It is designed for picker and resolved security-scoped URLs. A separate code path may access files already inside your container without a scope.

Test across relaunches

  • Pick a small fixture, read it, quit normally, and restore after launch.
  • Rename and move it while the app is closed. Verify the resolved selection and stale refresh.
  • Delete it, unmount its volume, and change permissions. Confirm a useful recovery action.
  • Cancel reselection and confirm the previous saved entry is preserved.
  • Inject storage failure and invalid bookmark data. Confirm errors do not produce a successful import.
  • Repeat open and failed-read loops while checking that successful starts are balanced.
  • Inspect release entitlements and test the signed sandboxed build, not only an unsandboxed command-line harness.
  • Confirm crash reports and support exports omit bookmark data and document paths.

Continue the macOS series with consistent Keychain queries, clipboard handling, and offline release verification.

References

Expanded from Ehsan's original bookmark post.

Authoritative References