iCloud在首次启动应用时无法工作

5
对于我的应用程序,我使用iCloud键值存储来存储一些用户设置。当iPad和iPhone都安装了该应用程序时,它可以在两者之间同步。但是,当我删除该应用程序并重新运行它时,第一次运行时它没有从iCloud中获取任何设置。即使第一次运行时没有设置,再次运行后它也会有。
我使用了一些NSLogs来查看键值容器中的内容,第一次新运行应用程序时,它显示“(null)”,但是任何后续运行都会打印出先前保存的NSArray。
我很乐意提供代码,但我不确定什么是相关的。
我会非常感谢任何帮助,这个问题让我发疯...
2个回答

6

NSUbiquitousKeyValueStoreDidChangeExternallyNotification添加观察者并同步NSUbiquitousKeyValueStore。等待回调很快就会被调用。

if([[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil])
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyValueStoreChanged:)
                                                 name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
                                               object:[NSUbiquitousKeyValueStore defaultStore]];

    [[NSUbiquitousKeyValueStore defaultStore] synchronize];
}
else
{
        NSLog(@"iCloud is not enabled");
}

然后使用NSUbiquitousKeyValueStoreChangeReasonKey来区分初次同步和服务器更改同步。

-(void)keyValueStoreChanged:(NSNotification*)notification 
{
    NSLog(@"keyValueStoreChanged");

    NSNumber *reason = [[notification userInfo] objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey];

    if (reason) 
    {
        NSInteger reasonValue = [reason integerValue];
        NSLog(@"keyValueStoreChanged with reason %d", reasonValue);

        if (reasonValue == NSUbiquitousKeyValueStoreInitialSyncChange)
        {
            NSLog(@"Initial sync");
        }
        else if (reasonValue == NSUbiquitousKeyValueStoreServerChange)
        {
            NSLog(@"Server change sync");
        }
        else
        {
            NSLog(@"Another reason");
        }
    }
}

好奇……为什么要在NSFileManager上使用-URLForUbiquityContainerIdentifier:方法? - Filip Radelic
检查设备是否启用了iCloud。 - erkanyildiz
1
注意:始终为所有其他原因提供备用方案。这非常重要。您可以将所有未处理的其他原因视为普通服务器更改的方式处理。 - Julien
最好的做法是使用switch语句,并有一个处理NSUbiquitousKeyValueStoreServerChange和所有其他情况的default: - Julien
@erkanyildiz 我明白了,直到现在我才发现这可能会在阅读文档时有所帮助。 - Filip Radelic

1

在您的应用程序安装(和启动)以及KVS下载初始值之间可能会存在延迟。如果您正确地注册更改通知,您应该能够看到值的到来。

您的代码应始终如此,通常在您的-applicationDidFinishLaunching:委托方法中:

_store = [[NSUbiquitousKeyValueStore defaultStore] retain]; // this is the store we will be using
// watch for any change of the store
[[NSNotificationCenter defaultCenter] addObserver:self
      selector:@selector(updateKVStoreItems:)
      name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
      object:_store];
// make sure to deliver any change that might have happened while the app was not launched now
[_store synchronize];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接