How iCloud sends a notification to my app when listening NSPersistentStoreDidImportUbiquitousContentChangesNotification

StackOverflow https://stackoverflow.com/questions/23499539

Question

I need to persist data on iCloud and on a web service through Core Data.

I would like to notify my app when the data on the web service have changed exactly like iCloud notifies my app when the data persisted on iCloud have changed.

To handle the notification for iCloud I have to push a listener on NSPersistentStoreDidImportUbiquitousContentChangesNotification and I would like to make the same mechanism for handle the modifications made on the data persisted on my web service.

So, I would like know how iCloud notifies my app to trigger NSPersistentStoreDidImportUbiquitousContentChangesNotification notification ? And how can I making the same thing between my web service and my app ?

Thanks !

Was it helpful?

Solution

Apple doesn't document the full process, but the goal is that you can treat NSPersistentStoreDidImportUbiquitousContentChangesNotification in almost the same way as NSManagedObjectContextDidSaveNotification. That is, you can merge changes from iCloud as if you were merging changes made on a different managed object context in your app.

The iCloud notification involves things that you don't have access to and can't duplicate on iOS. Specifically, it uses a separate process on iOS called the ubiquity daemon (ubd). That runs outside of your app and independently of it, and is responsible for communicating with the iCloud service to send/receive any new changes. When it receives new changes it updates your persistent store file and notifies your app. Since you can't run external processes on iOS, you couldn't duplicate the exact flow even if you knew what it was.

The closest you'll be able to get is to start up a separate thread or queue to duplicate as much of ubd as possible. That thread would:

  • Download new data from your web service
  • Create a new managed object context and save the new data using this context
  • Either wait a while and repeat the process, or exit and leave it to you to repeat it later on.

When those changes are saved, NSManagedObjectContextDidSaveNotification will be posted automatically. You can handle that in more or less the same way as you would handle NSPersistentStoreDidImportUbiquitousContentChangesNotification. If you want a notification that only occurs when your app receives new data from the web service, you can post that after saving those changes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top