Search code examples
macoscocoasandboxnsfilemanager

Can I delete a file on the Desktop from a sandboxed Mac app?


I can get my Mac app to read the contents of the Desktop, but whenever I try and delete a file it says I don't have permission to do so. If the user has authorized access to the Desktop, shouldn't I be able to delete a file?

  • Sandbox is turned on
  • File access is set to read/write for User Selected File.
  • The security scoped bookmarks are working because I have read access to the files, and it only comes up with the authorize prompt once.

This is the code I am using to delete:

[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
                                                     source:desktopPath
                                                destination:@""
                                                      files:self.filesToDelete
                                                        tag:nil];

I also tried using the fileManager trash method with no success.

Here is the error that returns from the fileManager trash method:

Error Domain=NSCocoaErrorDomain Code=513 "“file.png” couldn’t be moved to the trash because you don’t have permission to access it." UserInfo=0x60000026a980 {NSURL=file:///Users/me/Desktop/file.png, NSUserStringVariant=(
Trash
), NSUnderlyingError=0x600000257ca0 "The operation couldn’t be completed. (OSStatus error -5000.)"}

And the actual trash method call:

[[NSFileManager defaultManager] trashItemAtURL:url resultingItemURL:nil error:&error];

Solution

  • Unless the user has selected the file through an open dialog, or you saved the file through your app using a save dialog, you won't be able to delete it in a sandboxed app.

    There are a few directories where you can do what you want, mostly /tmp and the directories in your sandbox container.

    https://developer.apple.com/library/mac/documentation/security/conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html