Reputation: 1213
Is it possible to restore items put in the trash programmatically? I would like to have a "Move to Trash" button in my app, but I would like to be able to undo it without keeping my own copy. Is it inappropriate to be able to undo moving to trash, or should it be a permanent operation?
Upvotes: 5
Views: 1332
Reputation: 90551
Last time I checked, the Put Back feature was totally Finder-specific. That is, moving a file to the trash programmatically doesn't allow even the Finder to put it back. Only items trashed by the Finder can be put back by the Finder. (Even dragging an item from a folder on the Dock to the trash doesn't allow it to be put back, because the Dock trashed it, not the Finder.)
Even for an item which the Finder can put back, there's no documented way to do the Put Back operation programmatically.
However, for your own app, you can certainly undo the operation without keeping a separate copy of the file (until the user empties the trash). -[NSWorkspace recycleURLs:completionHandler:]
will give you the URLs for the items in the trash. Store the bookmark data for those URLs and the original containing folder, as well as the original name. To undo, resolve the bookmark data for the item in the trash and the original containing folder and move the former to the latter with the original name – except be sure to not clobber any new file that's been created in its place. If the move can't be completed without clobbering, try adding a suffix number to the file name. Keep incrementing until you find an unused name.
If resolving the bookmark data fails, then the operation couldn't be completed and you should let the user know.
Upvotes: 5