当应用程序处于后台模式时,如何才能错过CloudKit通知?

时间:2016-07-02 16:35:30

标签: ios swift cloudkit

  1. CloudKit 管理我的通知(不是我的专用服务器
  2. 我的第一个设备在 CloudKit容器中更改并推送通知。
  3. ...但在我的第二个设备上,我的应用目前正在后台模式下运行。所以......通知会通过提醒到达设备,但应用程序本身并不知道。
  4. 当应用返回到前台模式时,捕获这个错过通知(甚至更多)的优雅有效方法是什么?

    假设更改与我的顶级可见控制器相关,并且我希望在viewDidAppear:上不提取任何内容时应用该更改。

1 个答案:

答案 0 :(得分:0)

您只需执行以下操作即可在UIApplicationDelegate方法中实施:

func applicationWillEnterForeground(application: UIApplication) {

    var queryNotifications = [CKQueryNotification]()
    let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: nil)

    operation.notificationChangedBlock = { notification in

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

    operation.fetchNotificationChangesCompletionBlock = { token, error in

        var notificationIdentifiers = [CKNotificationID]()
        for queryNotification in queryNotifications {

            let recordID = queryNotification.recordID!

            //here you can do enything you need with your recordID
            container.publicCloudDatabase.fetchRecordWithID(recordID, completionHandler: { object, error in

                notificationIdentifiers.append(queryNotification.notificationID!)

                if queryNotifications.count == notificationIdentifiers.count {

                    let operationQueue = NSOperationQueue()
                    operationQueue.addOperation(CKMarkNotificationsReadOperation(notificationIDsToMarkRead: notificationIdentifiers))
                }
            })
        }
    }

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