Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force iCloud with core data to do sync?

I'm using iCloud with core data to sync data of my App.

I tried everything and finally It works perfectly.

but I have one question.

Is there any way that saying to iCloud to sync?

It sync when app begin, but the other time. It seems like that it sync randomly. I can't find the way to handle it myself.

any help?

Thanks.

like image 779
Bright Lee Avatar asked Nov 13 '22 02:11

Bright Lee


1 Answers

I figured out how to force a core data store to sync to iCloud. You just need to "touch" any receipt files in the Data folder in the Ubiquity filesystem. The code below will do this. To force a sync, call the syncCloud method. For every "receipt" file it finds, it will update the files modification time stamp to the current time, essentially doing a "touch" on the file. As soon as this happens, iCloud will check and sync any core data files that need synchronization in iCloud. Near as I can tell, this is how the simulator or Xcode does it when you select the "Trigger iCloud Sync" option.

@property (strong, nonatomic) NSMetadataQuery  *query;

-(void) init
{
    self.query = [[NSMetadataQuery alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(didFinishMetadataQuery)
                                                 name: NSMetadataQueryDidFinishGatheringNotification
                                               object: self.query];
}

-(void) didFinishMetadataQuery
{
    // Query completed so mark it as completed
    [self.query stopQuery];

    // For each receipt, set the modification date to now to force an iCloud sync
    for(NSMetadataItem *item in self.query.results)
    {
        [[NSFileManager defaultManager] setAttributes: @{NSFileModificationDate:[NSDate date]}
                                         ofItemAtPath: [[item valueForAttribute: NSMetadataItemURLKey] path]
                                                error: nil];
    }
}

-(void) syncCloud
{
    // Look for files in the ubiquity container data folders
    [self.query setSearchScopes:@[NSMetadataQueryUbiquitousDataScope]];

    // Look for any files named "receipt*"
    [self.query setPredicate:[NSPredicate predicateWithFormat:@"%K like 'receipt*'", NSMetadataItemFSNameKey]];

    // Start the query on the main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        BOOL startedQuery = [self.query startQuery];
        if (!startedQuery)
        {
            NSLog(@"Failed to start query.\n");
            return;
        }
    });
}
like image 144
John Cominio Avatar answered Nov 16 '22 04:11

John Cominio