3

Is there a way to detect if a file located on iCloudDrive has been moved to the iCloudDrive trash? I could check the URL to contain ".Trash" but I am looking for an official way to retrieve this.

berbie
  • 978
  • 10
  • 13

2 Answers2

4

To detect if a file/folder is in Trash use following code:

NSURLRelationship relationship;
NSError *error;
[[NSFileManager defaultManager] getRelationship:&relationship ofDirectory:NSTrashDirectory inDomain:0 toItemAtURL:URL error:&error];
if (relationship == NSURLRelationshipContains) {
    //file is in trash
}
Marek H
  • 5,173
  • 3
  • 31
  • 42
  • Please add a brief description of what your code is doing, else this question can be easily considered as low quality. – briosheje Nov 20 '17 at 16:32
  • There is some trouble with this code: 1. It ignores `error`, and this means that if `relationship` is pre-inited to zero, it'll give the wrong result if there's an error. 2. It does not work with files trashed from an iCloud folder (e.g. if, in Catalina, Deskop and Documents folders are synched to iCloud), into `~/Library/Mobile Documents/com~apple~CloudDocs/.Trash`, because then an error is returned (Code=3328 "The requested operation couldn’t be completed because the feature is not supported.") – Thomas Tempelmann Nov 03 '20 at 13:15
  • Note: My second part of the previous comment is for macOS, not iOS. – Thomas Tempelmann Nov 03 '20 at 13:22
  • Also note that if the item is a symlink, and if that symlink now points to nowhere (i.e. not to an existing file or folder), you'll also get the error 3328. See https://stackoverflow.com/q/64663834/43615 – Thomas Tempelmann Nov 10 '20 at 12:27
2

Found a decent way to detect this. Starting with iOS11 the following approach is possible:

NSURL* fileURL; // any file URL pointing to a file resource
NSURL* trashURL = [NSFileManager.defaultManager URLForDirectory:NSTrashDirectory inDomain:NSUserDomainMask appropriateForURL: fileURL create:NO error:NULL];
if (trashURL && [fileURL.path hasPrefix:trashURL.path])
{
    // fileURL is located in the iCloudDrive trash
}
berbie
  • 978
  • 10
  • 13
  • 1
    Make sure that you get the canonical path of your fileURL before testing it in this way, i.e. by getting the NSURLCanonicalPathKey or by calling `[NSString stringByResolvingSymlinksInPath]`. Without that, you may be using a path that points to the Trash via symlinks and then your check would not work. – Thomas Tempelmann Nov 10 '20 at 12:29