如何从iCloud获取所有待处理的通知并通知它我的应用收到了通知?

时间:2017-01-16 12:44:39

标签: ios swift cloudkit

通常我会在记录更改时立即收到通知。

但是当我的应用没有运行时该怎么办,我需要获取所有待处理的通知?

1 个答案:

答案 0 :(得分:0)

简单地这样做:

func fetchPendingNotifications() {

    var queryNotifications = [CKQueryNotification]()

    let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: nil)
    let operationQueue = OperationQueue()

    operation.notificationChangedBlock = { notification in

        if let queryNotification = notification as? CKQueryNotification {
            queryNotifications.append(queryNotification)
        }
    }

    operation.fetchNotificationChangesCompletionBlock = { _, error in

        if error == nil {

            self.perform(queryNotifications: queryNotifications) { _ in

                //do sth on success
            }
        }
    }

    operationQueue.addOperation(operation)
}

辅助函数是:

private func perform(queryNotifications: [CKQueryNotification], completion: ErrorHandler? = nil) {

    var currentQueryNotifications = queryNotifications

    if let queryNotification = currentQueryNotifications.first {

        currentQueryNotifications.removeFirst()

        if queryNotification.queryNotificationReason == .recordCreated || queryNotification.queryNotificationReason == .recordUpdated {

            //fetch the record from cloud and save to core data
            self.fetchAndSave(with: queryNotification.recordID!) { error in 

                if error == nil {

                    OperationQueue().addOperation(CKMarkNotificationsReadOperation(notificationIDsToMarkRead: [queryNotification.notificationID!]))
                    self.perform(queryNotifications: currentQueryNotifications, completion: completion)

                } else {
                    completion?(error)
                }
            }

        } else {
            //delete record from coredata
            self.delete(with: queryNotification.recordID!) { error in

                if error == nil {

                    OperationQueue().addOperation(CKMarkNotificationsReadOperation(notificationIDsToMarkRead: [queryNotification.notificationID!]))
                    self.perform(queryNotifications: currentQueryNotifications, completion: completion)

                } else {
                    completion?(error)
                }
            }
        }

    } else {

        completion?(nil)
    }
}