Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put Back Items from Trash Programmatically

Tags:

macos

cocoa

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?

like image 460
Josh The Geek Avatar asked Sep 09 '13 21:09

Josh The Geek


People also ask

How do you move items back from the Trash on a Mac?

On your Mac, click the Trash icon in the Dock. Drag the item out of the Trash, or select the item, then choose File > Put Back.

How do I restore multiple items from Trash on Mac?

So as you know, if you click on the trash icon in your Dock, you will see the items you have, well, trashed. Right-click or Control-click on any file (or hold down Command to click and select multiple items, then Control-click), and you will see the Put Back option.


1 Answers

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.

like image 160
Ken Thomases Avatar answered Sep 22 '22 03:09

Ken Thomases