How to set up a minimal CKSubscription?

爷,独闯天下 提交于 2019-12-03 02:57:31

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
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!