Search code examples
iosiclouduidocument

Proper way to detect deletion of documents in iCloud across devices?


I can't find an obvious way to detect deletion of a document that I'm monitoring (I cache a list of docs my app cares about).

On Device1: When I delete a doc, I call

        [fileCoordinator coordinateWritingItemAtURL:fileURL options:NSFileCoordinatorWritingForDeleting
          error:&err byAccessor:^(NSURL* writingURL) {
             [fileManager removeItemAtURL:writingURL error:nil];

This works fine on Device1, everything stays in synch. On Device2: I was trying to rely on NSMetadataQuery notifications:

Initial file list is coming in fine on NSMetadataQueryDidFinishGatheringNotification Document adds/changes are coming in fine via NSMetadataQueryDidUpdateNotification

When i delete a file on Device1, I get a strange result: an update comes in NSMetadataQueryDidUpdateNotification with all my docs (except the one deleted) listed I'm not sure how I am supposed to detect that the missing file was deleted or that the update notification was for that purpose

Question 1: What should I be checking for?

I tried another route which was to register as a NSFilePresenter for the iCloud URL:

- (NSURL *)iCloudDocumentsURL
{
    return [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:@"Documents"];
}

I now get called via the NSFilePresenter protocol when files in that URL change, but it's punitively slow to run the logic to determine the missing doc since the callback is vague. The only call I get back is - (void)presentedItemDidChange; I was expecting to get a callback via - (void)accommodatePresentedSubitemDeletionAtURL:(NSURL *)url completionHandler:(void (^)(NSError *errorOrNil))completionHandler But this method is never called.

Question 2: Any idea how to get that working?


Solution

  • Since you're keeping track of files previously reported from iCloud, the deleted file is absent from the current iCloud listing, and so you just compare the two lists to find which was deleted.

    That's what I'm doing in my "file manager" view controller, because I keep a NSMutableDictionary of file entries, which includes among other things, keys for the positions of the file "icons" in my master view. When I get notified of an update, and that update results in either more or fewer files, I animate the icon changes based upon those file changes.