3

I am adding subscription to a Cloud Kit record type with FireOnCreation.

In the appDelegate, I used the didReceiveRemoteNotificationWithCompletionHandler to catch the notification. The issue I am having is when a record is created matching the predicate, the didReceiveRemoteNotificationWithCompletionHandler would trigger multiple time. On device A, it would trigger 3 times consistently and where on device B, it would trigger 6 times. I even tried to create a record on the Cloud DashBoard and it would still do the same thing. So that tells be the issue is not with the record creation. Any suggestion or hints would be of great help.

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
}

func subscribeRecordChangesForCurrentUser(userRecordID: CKRecordID) {
    print("subscribeRecordChangesForCurrentUser \(userRecordID.recordName)")
    let userRef = CKReference(recordID: userRecordID, action: CKReferenceAction.None)
    let predicate = NSPredicate(format: "toUsers CONTAINS %@", userRef)
    let subscription = CKSubscription(recordType: "Track", predicate: predicate, options: [.FiresOnRecordCreation])

    let notificationInfo = CKNotificationInfo()
    notificationInfo.alertBody = "Created a new track."
    notificationInfo.shouldSendContentAvailable = true
    notificationInfo.soundName = UILocalNotificationDefaultSoundName

    subscription.notificationInfo = notificationInfo

    let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase

    publicDatabase.saveSubscription(subscription) { (subscription: CKSubscription?, error: NSError?) -> Void in
        guard error == nil else {
            print(error?.localizedDescription)
            return
        }
        print("successfully subscript user")
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
HioChao
  • 215
  • 1
  • 7

1 Answers1

3

You might have multiple subscriptions on those devices. When you create a new subscription, delete the old ones.

Take a look at

CKDatabase.fetchAllSubscriptionsWithCompletionHandler(_:)

For a quick and dirty fix, I believe you can remove the app from the device and reinstall it.

MirekE
  • 11,515
  • 5
  • 35
  • 28
  • 1
    Thanks for the response. That is exactly what I neglected to do. I thought deleting the subscription from the Cloud Dashboard would be enough. Apparently it isn't and I found that the cloud container is dirty. In the end, I have to reset the development environment. Now, I use the CKModifySubscriptionsOperation method to delete old and save new subscriptions. And I use the fetchAllSubscriptionsWithCompletionHandler to fetch all current subscriptions that are to be deleted. – HioChao Dec 22 '15 at 04:42