当应用程序处于后台模式时,如何错过 CloudKit 通知?
How can I get missed CloudKit notification while app is in the background mode?
- CloudKit 管理我的通知(不是我的专用服务器)
- 我的 第一个 设备在 CloudKit 容器 中更改某事并推送通知。
- ...但是在我的 second 设备上,我的应用目前 运行 处于后台模式。所以...通知通过 Alert 到达设备,但应用程序本身并不知道。
当应用程序返回前台模式时,捕捉这个(或更多)错过的通知的优雅有效的方法是什么?
假设更改与我的顶部可见控制器相关,我想应用该更改而不在 viewDidAppear:
上获取任何内容。
您可以简单地执行以下操作,在 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)
}
- CloudKit 管理我的通知(不是我的专用服务器)
- 我的 第一个 设备在 CloudKit 容器 中更改某事并推送通知。
- ...但是在我的 second 设备上,我的应用目前 运行 处于后台模式。所以...通知通过 Alert 到达设备,但应用程序本身并不知道。
当应用程序返回前台模式时,捕捉这个(或更多)错过的通知的优雅有效的方法是什么?
假设更改与我的顶部可见控制器相关,我想应用该更改而不在 viewDidAppear:
上获取任何内容。
您可以简单地执行以下操作,在 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)
}