iCloud无法在第一次启动应用程序时运行

Dan*_*lik 5 cocoa-touch objective-c ios icloud

对于我的应用程序,我使用iCloud键值存储来存储一些用户设置.当两者都安装了应用程序时,它在我的iPad和iPhone之间完美同步.我的问题是,当我删除应用程序,并且我重新运行它时,它没有iCloud的任何设置,我第一次运行它.在我再次运行它之后,即使它第一次没有设置,它也有它们.

我使用了一些NSLog来查看它在键值容器中看到的内容,并且第一次应用程序运行时它会显示"(null)",但是任何后续运行它都会打印出先前保存的NSArray.

我很乐意提供代码,但我不完全确定这里的相关内容.

我很感激任何帮助,这个问题让我发疯...

erk*_*diz 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");
}
Run Code Online (Sandbox Code Playgroud)

然后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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)