NSUbiquityIdentityDidChangeNotification 和 SIGKILL

NSUbiquityIdentityDidChangeNotification and SIGKILL

Swift 1.2 Xcode6

长期倾听者,首次调用者。

您好,

直接从马嘴里说出来:"To handle changes in iCloud availability, register to receive the NSUbiquityIdentityDidChangeNotification notification."

这是他们提供的实现此代码的代码:

[[NSNotificationCenter defaultCenter]

addObserver: self

   selector: @selector (iCloudAccountAvailabilityChanged:)

       name: NSUbiquityIdentityDidChangeNotification

     object: nil];

我在我的应用程序中Swift将其修改为:

var observer = NSNotificationCenter.defaultCenter().addObserverForName
(NSUbiquityIdentityDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()
){...completion block...}

来源:https://developer.apple.com/library/ios/documentation/General/Conceptual/iCloudDesignGuide/Chapters/iCloudFundametals.html#//apple_ref/doc/uid/TP40012094-CH6-SW6

实现这个的正确方法是什么?它会进入 AppDelegate 吗?当应用程序被发送到后台时,我们是否删除观察者?

我遇到的问题是,当 Ubiquity Token 更改时,应用程序无论如何都会终止,因为用户已更改 iCloud 设置。

你们是如何设法订阅这个通知的,如果不订阅,你们会做什么来跟踪当前登录的 iCloud 用户?

谢谢!

我发现了同样的问题,请参阅 this question 以获取我的评论。

总结一下:关于 iOS 我认为当 iCloud 帐户更改(或刚刚注销)时,应用程序无论如何都会被终止。所以不用听NSUbiquityIdentityDidChangeNotification.

但是,如果您使用的是 tvOS,则您的应用不会被终止。当您的应用程序激活时,您确实会收到一个或多个 NSUbiquitousKeyValueStoreDidChangeExternallyNotification,其中 NSUbiquitousKeyValueStoreChangeReasonKey 设置为 NSUbiquitousKeyValueStoreAccountChange,因为 tvOS 交换了您的整个无处不在 key-value-store。

也许您可以使用它和一些技巧来检测帐户更改,例如在无处不在的key-value-store中存储一个NSUUID,当值发生变化时,表示有一个新帐户。但是您无法检测到帐户是否已注销。

简答

要在用户使用您的应用程序登录或注销 iCloud 时在 iOS 中收到通知,请使用 CKAccountChangedNotification,而不是 NSUbiquityIdentityChanged

长答案

我也一直在努力让它发挥作用。我记得在 WWDC16 的一次演讲中,他们推荐使用 something 这样的东西。但是,从他们提供的示例代码中,我只能找到 NSUbiquityKeyIdentityChanged,我无法开始工作。

所以我回到了the video (it's from 2015)。这就是我看到他们提到 CKAccountChangedNotification 的地方——它完全按照预期工作:

  • 从 Xcode
  • 在模拟器上启动您的应用程序
  • 退出到模拟器上的“设置”应用程序
  • 登录(或注销)iCloud 帐户
  • 返回您的应用程序(点击模拟器主屏幕上的图标)
    • 收到通知。
  • 再次退出设置应用程序
  • 注销(或登录)到 iCloud 帐户
  • 再次返回您的应用
    • 收到另一个通知。

Swift 3.0中还有一个重命名:

现在NSUbiquityIdentityDidChangeNotification变成了NSNotification.Name.NSUbiquityIdentityDidChange

所以完整的注册如下:

// Register for iCloud availability changes
NotificationCenter.default.addObserver(self, selector: #selector(...), name: NSNotification.Name.NSUbiquityIdentityDidChange, object: nil)

在 iOS 10 我发现 NSUbiquityIdentityDidChangeNotification 从未发送过。如果我有一个 CKContainer(根据文档),CKAccountChangedNotification 是在非常有限的情况下发送的。

使用 xCode 9.1 构建,然后在 iOS 10.02 iPhone 6+ 和 iOS 11.0.3 iPhone SE

上进行测试

CKAccountChangedNotification 已发送,如果

  • 用户登录到 iCloud 帐户,或者
  • 用户在 iOS11 中启用了 iCloud Drive。这总是导致启用 iCloud Drive->App。但是,之后获取帐户状态产生了 NoAccount!
  • 用户在iOS10启用了iCloud Drive,之后iCloud Drive->App的状态就是我禁用iCloud Drive时的状态。帐户状态是适当的。但是,如果此时禁用 iCloud Drive->App,则启用它不会产生终止或通知。

如果

,应用程序被终止
  • 无论 iCloud Drive 状态如何,用户都退出了 iCloud
  • 用户禁用了 iCloud Drive->App
  • 用户禁用了 iCloud Drive(即使 iCloud Drive->App 已经禁用)
  • 用户在启用 iCloud Drive 的情况下启动应用程序,然后启用 iCloud Drive->App