Tuesday, April 23, 2013

NSFileManager trashItemAtURL example


trashItemAtURL :resultingItemURL:error:

Moves an item to the trash.
- (BOOL)trashItemAtURL:(NSURL *)url resultingItemURL:(NSURL**)outResultingURL error:(NSError **)error
Return Value of [NSFileManager trashItemAtURL]
YES if the item at url was successfully moved to the trash. Since the operation may require renaming the item to avoid a file name collision, this method returns, by reference, the resulting URL that the item was moved to.
If this method returns NO, the item was not moved to the trash; the error parameter then contains information about the error.
Example of [NSFileManager trashItemAtURL]

#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSFileManager *fm = [NSFileManager defaultManager];
        if (argc == 1) {
            fprintf(stderr, "Please supply one or more file names.\n");
            return 1;
        }
        for (int i=1; i < argc; i++) {
            const char* file_to_trash = argv[i];
            NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:file_to_trash]];
            NSURL *trashed;
            NSError *error;
            if ([fm trashItemAtURL:url resultingItemURL:&trashed error:&error]) {
                fprintf(stdout, "Trashed %s to %s\n", [[url path] UTF8String], [[trashed path] UTF8String]);
            } else {
                fprintf(stderr, "Failed to trash %s: %s\n", [[url path] UTF8String], [[error localizedDescription] UTF8String]);
                return 1;
            }
        }
    }
    return 0;
}