I have a problem with programmatically deleting files that reside on an external disk,
which must be accessed using security-scoped bookmarks.
In my app, I collect lists of files that reside on an external disk.
After the user has opened the directory of the files, I create a security-scoped bookmark like this:
directoryBookmark_ = [dir bookmarkDataWithOptions: NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys: nil
relativeToURL: nil
error: &systemError];
Next time, the app runs, I resolve the bookmark like this:
directoryLocation_ = [NSURL URLByResolvingBookmarkData: directoryBookmark_
options: NSURLBookmarkResolutionWithSecurityScope
relativeToURL: nil
bookmarkDataIsStale: & isStale
error: & error];
[directoryLocation_ startAccessingSecurityScopedResource];
(directoryBookmark_ is saved and loaded in the user preferences.)
At some later point, my app wants to delete one of the files in that directory (or sub-directory),
like this:
NSString * abs_path = [self absolutePathFor: filename_];
BOOL success = [self deleteFile: abs_path ];
This does not work. In the log, I get the error message:
Failed to delete /Volumes/.../image.jpg: “image.jpg” couldn’t be moved to the trash because you don’t have permission to access it.!
I then try to get more info about the problem using this code:
NSURL * imgurl = [NSURL fileURLWithPath: abs_path isDirectory: NO];
NSError * error;
NSFileHandle * fileHandle = [NSFileHandle fileHandleForUpdatingURL: imgurl error: & error];
But it always returns a valid fileHandle, i.e., there is no error.
I selected "Read/Write" in the "User Selected File" entitlement of my app.
Of course, everything works fine when the files reside on my local disk (even across multiple invocations of the app).
The external disk is just a hard disk connected via USB to my laptop.
Deleting the files manually on the external hard disk works, of course.
Does anyone have an idea what mistake I might be making?
Or is there a way to get the necessary permission?
Surely, apps must have a way of deleting files programmatically, don't they?
At least, appe's docs don't mention anything indicating otherwise.
All hints and insights will be highly appreciated.