0

I am currently using code similar to the following to upload to my iCloud container:

NSData * data = ...;

NSURL * documentsURL =
    [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier: @"com.somecontainer.id"] URLByAppendingPathComponent: @"Documents"];

NSURL * cloudFileURL =
    [NSURL fileURLWithPath: [documentsURL.path stringByAppendingPathComponent: @"test.sql"]];

if(nil != documentsURL &&
   ![[NSFileManager defaultManager] fileExistsAtPath: documentsURL.path])
{
    [[NSFileManager defaultManager] createDirectoryAtURL: documentsURL
                             withIntermediateDirectories: YES
                                              attributes: nil
                                                   error: NULL];
} // End of does not exist

[dataToSave writeToURL: cloudFileURL
               options: NSDataWritingAtomic
                 error: error];

This works fine and it writes the data to my iCloud container, but if I try and query the container quickly using the following:

filesMetadataQuery = [NSMetadataQuery new];
filesMetadataQuery.searchScopes = @[NSMetadataQueryUbiquitousDocumentsScope];
filesMetadataQuery.predicate = [NSPredicate predicateWithFormat:@"%K like '*.sql'", NSMetadataItemFSNameKey];

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(queryDidFinishGathering:)
                                             name: NSMetadataQueryDidFinishGatheringNotification
                                           object: nil];

[filesMetadataQuery startQuery];

The file does not show up UNLESS I delay the startQuery a few seconds. I would think that once writeToURL: (which is a blocking call) finishes, the NSMetadataQuery should be able to find it right away, but this does not seem to be so.

Is there an alternative way I can upload to my iCloud container and verify that everything has finished?

Kyle
  • 17,317
  • 32
  • 140
  • 246

1 Answers1

0

I wrapped this in a NSFileCoordinator and it seems to have resolved the issue.

NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter: nil];
__block NSError * saveError = nil;

[coordinator coordinateWritingItemAtURL: targetURL
                                options: 0
                                  error: error
                             byAccessor: ^(NSURL *url) {
                                 [dataToSave writeToURL: url
                                                options: NSDataWritingAtomic
                                                  error: &saveError];
                             }];

Now if I run a NSMetadataQuery directly after, the file is found.

Kyle
  • 17,317
  • 32
  • 140
  • 246