kevinchooski kevinchooski - 1 year ago 148
Swift Question

NSUbiquityIdentityDidChangeNotification and SIGKILL

Swift 1.2
Xcode 6

Long-time listener, first-time caller.


Straight from the horse's mouth: "To handle changes in iCloud availability, register to receive the NSUbiquityIdentityDidChangeNotification notification."

Here is the code they provide to implement this:

[[NSNotificationCenter defaultCenter]

addObserver: self

selector: @selector (iCloudAccountAvailabilityChanged:)

name: NSUbiquityIdentityDidChangeNotification

object: nil];

I Swiftified it in my app to:

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


What is the correct way to implement this? Does it go in the AppDelegate? Do we remove the observer when the app gets sent to the background?

The problem I'm encountering is that when the Ubiquity Token changes, the app is terminated anyway because the user has changed iCloud settings.

How do you all manage to subscribe to this notification, and, if you don't, what do you do instead to keep track of the current logged in iCloud user?

Thank you!

Answer Source

Short Answer

To be notified in iOS when a user logs in or out of iCloud while using your app, use CKAccountChangedNotification, not NSUbiquityIdentityChanged.

Long Answer

I've been trying to get this to work as well. I remembered something from one of the talks at WWDC16 that there was something like this that they recommended to use. However, from the sample code they provide, I've only been able to find NSUbiquityKeyIdentityChanged, which I haven't been able to get to work.

So I went back to the video (it's from 2015). That's where I saw them refer to CKAccountChangedNotification – and it works exactly as expected:

  • Launch your app on the simulator from Xcode
  • Exit to the Settings app on the simulator
  • Log in (or out) of iCloud account
  • Go back into your app (tap icon on simulator home screen)
    • A notification is received.
  • Exit to Settings app again
  • Log back out (or in) to iCloud account
  • Go back into your app again
    • Another notification is received.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download