10

I want to set up a simple CKSubscription that notifies me a recordType was created, how?

János
  • 32,867
  • 38
  • 193
  • 353

2 Answers2

13

After experimenting a while this is how to setup a minimal CKSubscription. You have to test it on Device, push notification does not work on simulator. You can add record in Dashboard, that will trigger push notification too.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
    application.registerForRemoteNotifications()
        return true
}

func someFunc() { // <- you need to call once in app life time, and again when it was removed / installed 
     let defaultContainer = CKContainer.defaultContainer()
     let publicDatabase = defaultContainer.publicCloudDatabase   
     let subs = CKSubscription(recordType: "xxx", predicate: NSPredicate(value: true), subscriptionID: "yyy", options: .FiresOnRecordCreation)
     subs.notificationInfo = CKNotificationInfo()
     subs.notificationInfo.alertBody = "New item added"
     publicDatabase.saveSubscription(subs, completionHandler: {subscription, error in})
}

func application(application: UIApplication!, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]!)
{
    // <- this method will invoked
}
János
  • 32,867
  • 38
  • 193
  • 353
  • it is important that if `alertBody = ""` then no alert view will appear when app is off, at least an empty character you have to set – János Aug 11 '15 at 12:25
3

Did you register for notifications? You should have something like this in your application didFinishLaunchingWithOptions:

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert | .Badge | .Sound, categories: nil))
application.registerForRemoteNotifications()

I created a working demo that is available at https://github.com/evermeer/EVCloudKitDao

Edwin Vermeer
  • 13,017
  • 2
  • 34
  • 58
  • checking your code, do I need to create at each launch subscription, or only once in the life time of the app to get the notification – János Jul 23 '14 at 16:05
  • No, you only need to create a subscription once. If you try to create the exact same subscription you will get an error that a similar subscription already exists. – Edwin Vermeer Jul 23 '14 at 21:09
  • yes, but after I stop the app and restart it again I can recreate it, and also I can create subscription from other device with same name, is it right?! – János Jul 24 '14 at 00:23
  • 1
    when you recreate it, you should see an error that it already exist. Since it's already there you could ignore that error. If you create it on another device, but the same iCloud id, then you should still see that error. If you create it using a different iCloud id, then it's OK – Edwin Vermeer Jul 24 '14 at 07:58