【问题标题】:iCloud connects on simulator but not on deviceiCloud 在模拟器上连接,但不在设备上
【发布时间】:2014-05-02 11:03:16
【问题描述】:


我是 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 块,如果我在模拟器或未连接的设备上测试它,一切正常。
非常感谢。
weissja19

【问题讨论】:

  • 您能否分享一下您是如何连接到 iCloud 的,以及可能会出现故障的地方?

标签: ios ios-simulator icloud


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2012-12-21
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多