如何强制iCloud与核心数据进行同步?

时间:2012-07-01 13:09:25

标签: iphone ios5 icloud

我正在使用带有核心数据的iCloud来同步我的应用程序的数据。

我尝试了一切,最后它完美无缺。

但我有一个问题。

有没有办法说iCloud同步?

它在应用开始时同步,但另一次。它似乎随机同步。我找不到自己处理它的方法。

任何帮助?

感谢。

3 个答案:

答案 0 :(得分:1)

我想出了如何强制核心数据存储同步到iCloud。你只需要触摸" Ubiquity文件系统中Data文件夹中的任何收据文件。下面的代码将执行此操作。要强制同步,请调用syncCloud方法。对于每个"收据"它找到的文件,它会将文件修改时间戳更新为当前时间,基本上是一个" touch"在文件上。一旦发生这种情况,iCloud将检查并同步任何需要在iCloud中同步的核心数据文件。我可以说,这就是当您选择" Trigger iCloud Sync"时,模拟器或Xcode如何做到这一点。选项。

@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;
        }
    });
}

答案 1 :(得分:0)

您必须使用此方法强制在iCloud中缓存任何NSURL项目:

- (BOOL)addBackupAttributeToItemAtURL:(NSURL *)URL
{
    NSLog(@"URL: %@", URL);
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: NO]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
    return success;
}

您需要在Documents / Library目录中下载/创建的每个目录和文件上启动此方法。

答案 2 :(得分:0)

我不相信您在使用iCloud和核心数据时可以控制何时发生同步。使用UIDocument和iCloud,我使用了startDownloadingUbiquitousItemAtURL并取得了不同程度的成功,但对于核心数据,我认为没有任何等价物 - 我很乐意听到有人告诉我,不过...

相关问题