ios - iCloud 在模拟器上连接但不在设备上

标签 ios ios-simulator icloud


我是 iOS 编程的新手,现在我遇到了一个问题,如果我在真实设备上运行我的应用程序,我将无法获得 iCloud 连接。
该应用程序在模拟器上运行完美,即使我断开设备与 mac 的连接也是如此。
有人知道我该如何解决吗?
这是我为连接到 iCloud 而编写的代码

    self.fileManager = [NSFileManager defaultManager];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.ubiquityIdentifier = [self.fileManager URLForUbiquityContainerIdentifier:nil];
    });

    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.ubiquityIdentifier)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:kiCloudAvailableNotification object:self.ubiquityIdentifier];
            [self startMediaQuery];
        }
        else
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:kiCloudNotAvailableNotification object:self.ubiquityIdentifier];
            NSLog(@"iCloud not available");
        }
    });

如果设备已连接,我只进入 else block ,如果我在模拟器或未连接的设备上测试它,一切正常。
非常感谢。
weissja19

最佳答案

假设您检测到失败是因为 NSLog 打印了它的“iCloud 不可用”消息,您在这里设置了一个经典的竞争条件:

  1. 您在全局(非主)队列上设置 self.ubiquityIdentifier 的值。
  2. 您在主队列上测试self.ubiquityIdentifier

这两个 dispatch_async 调用在不同的队列上运行。因此,无法保证您在测试之前设置了 self.ubiquityIdentifier 的值。它有时会奏效,有时会失败,而且不一定出于任何明显的原因。当您收到“iCloud 不可用”消息时,这是因为第二个队列在您分配任何值之前检查了该值。

修复方法是更改​​调度调用,以便您可以保证执行顺序。两种可能性是:

  1. 合并这两个 dispatch_async 调用,以便所有代码都发生在同一个队列中,或者
  2. 将第二个 dispatch_async 移到第一个 中,这样在为 self 设置值之前,您不会分派(dispatch)回主队列。 ubiquityIdentifier.

关于ios - iCloud 在模拟器上连接但不在设备上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22620429/

相关文章:

xcode - Mac 键盘快捷键在 iOS 模拟器上不起作用

objective-c - 调用-[NSFileManager setUbiquitous :itemAtURL:destinationURL:error:] never returns

ios - 如何在使用照片框架从照片中选取图像时隐藏选取器中的 iCloud 图像

ios - 从第二个 View Controller 中关闭一组具有自定义动画的 Controller

iOS Instagram 每次登录问题

iphone - 在 View 之间传递 IndexPath

iOS 8 测试版 OSStatus -34018 (errSecMissingEntitlement)

ios-simulator - 如何将视频添加到 iOS7.1 模拟器 Xcode 6

ios - MVP 架构模式示例。 swift

iphone - 防止从 iCloud 中的应用程序备份