shle2821
shle2821

Reputation: 1886

CloudKit sends multiple push notifications even after removing CKSubscription and readding them

I set the CKSubscription to "fire on record creation" for a table. And when there is a need for me to update that particular instance of CKSubscription, I make sure to remove it first before adding it.

But now whenever I save a new CKRecord, i'm get four same instances of push notification. Has anyone experienced this? If so is there a workaround for this issue?

Upvotes: 0

Views: 219

Answers (1)

user3069232
user3069232

Reputation: 8995

Yes, you need to tell it you treated the notifications, with code like this?

func fetchNotificationChanges() {
    let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: nil)

    var notificationIDsToMarkRead = [CKNotificationID]()

    operation.notificationChangedBlock = { (notification: CKNotification) -> Void in
        // Process each notification received
        if notification.notificationType == .query {
            let queryNotification = notification as! CKQueryNotification
            let reason = queryNotification.queryNotificationReason
            let recordID = queryNotification.recordID

            print("reason \(reason)")
            print("recordID \(recordID)")
            // Do your process here depending on the reason of the change

            // Add the notification id to the array of processed notifications to mark them as read
            notificationIDsToMarkRead.append(queryNotification.notificationID!)
        }
    }

    operation.fetchNotificationChangesCompletionBlock = { (serverChangeToken: CKServerChangeToken?, operationError: Error?) -> Void in
        guard operationError == nil else {
            // Handle the error here
            return
        }

        // Mark the notifications as read to avoid processing them again
        let markOperation = CKMarkNotificationsReadOperation(notificationIDsToMarkRead: notificationIDsToMarkRead)
        markOperation.markNotificationsReadCompletionBlock = { (notificationIDsMarkedRead: [CKNotificationID]?, operationError: NSError?) -> Void in
            guard operationError == nil else {
                // Handle the error here
                return
            }
        }

        let operationQueue = OperationQueue()
        operationQueue.addOperation(markOperation)
    }

    let operationQueue = OperationQueue()
    operationQueue.addOperation(operation)
}


}

Upvotes: 1

Related Questions