Search code examples
iosswiftcloudkitcksubscription

CloudKit subscriptions in the private database


I have an app for which I want to add the possibility to backup data to iCloud using CloudKit. The "backup" part seems to work correctly (my records are in the private database, since they are ... well, private).

Now I would like to use CKSubscriptions to keep all my devices in sync with the same data. I tried to implement a CKSubscription to monitor record creation / update / deletion based on a query (not based on zones).

func subscribe() {

  let options = CKSubscriptionOptions.FiresOnRecordCreation |
  CKSubscriptionOptions.FiresOnRecordDeletion |
  CKSubscriptionOptions.FiresOnRecordUpdate


  let predicate = NSPredicate(value: true) // get all the records for a given type
  let subscription = CKSubscription(recordType: "Stocks",
  predicate: predicate, subscriptionID: subscriptionID,
  options: options)

  subscription.notificationInfo = CKNotificationInfo()
  subscription.notificationInfo.alertBody = ""

  db.saveSubscription(subscription, completionHandler: {
  subscription, error in
    if (error != nil) {
      println("error subscribing: \(error)")
    } else {
      println("subscribed!")
    }
  })
}

Until now, I haven't been able to trigger a notification to my device.

I know that you can create a subscription based on zones. Zones are in the private DB, so I suppose that CKSubscriptions could work in the private DB. But I didn't want to implement zones (that I don't need otherwise).

Question: is there an issue with CKSubscriptions in the private DB based on a query ?


Solution

  • This should work. Non zone subscriptions (query based subscriptions) are supported on private databases. Did you add the code to receive notifications in your AppDelegate?