Search code examples
filecocoasandbox

Cocoa sandbox - reopen files when restarting app


I have a sandboxed Cocoa app. It has a one window, multi-tabbed UI. I don't use NSDocument, but it is an app that can edit multiple "documents". When the app closes I save a list of the open documents. When I restart the apps, I try to re-open them in tabs.

This works fine when all the document files are in the sandboxed documents directory. However, users can also open files outside the sandbox. When the app is restarted, these files cannot be opened because of sandbox permissions, the file is not readable. I do understand that normally the user has to chose the out-of-sandbox file from an open dialog.

The files are in the "Recent Files" list and can be opened that way.

There must be a way to do this since that is how most text editors work. Is there a magic entitlement or call I'm missing?


Solution

  • You need security-scoped bookmarks.

    Check out the Security-Scoped Bookmarks and Persistent Resource Access section of the Apple's App Sandbox Design Guide.

    Your app’s access to file-system locations outside of its container—as granted to your app by way of user intent, such as through Powerbox—does not automatically persist across app launches or system restarts. When your app reopens, you have to start over.
    ...
    Starting in OS X v10.7.3, you can retain access to file-system resources by employing a security mechanism, known as security-scoped bookmarks, that preserves user intent.

    I'd summarize it here, but the above link has everything you need.