gpt4 book ai didi

swift - 如何对大量入站 CloudKit 通知进行排队

转载 作者:行者123 更新时间:2023-11-30 11:16:33 69 4
gpt4 key购买 nike

假设我使用 CKModifyRecordsOperation 向 CloudKit 保存 50 条记录,如下所示:

let operation = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: nil)
operation.savePolicy = .changedKeys

operation.modifyRecordsCompletionBlock = { records, _, error in
//...
}

privateDB.add(operation)

在我的其他设备上,对于每个发生更改的 CKRecord,我都会收到 50 种不同的后台通知。很好,我希望如此。

我像这样处理每个入站通知:

func processCloudKitNotification(notification: CKNotification, database: CKDatabase){

guard let notification = notification as? CKQueryNotification else { return }

if let recordID = notification.recordID{
var recordIDs = [CKRecordID]()

switch notification.queryNotificationReason {
case .recordDeleted:
//Delete [-]
//...
default:
//Add and Edit [+ /]
recordIDs.append(recordID)
}

let fetchOperation = CKFetchRecordsOperation(recordIDs: recordIDs)

fetchOperation.fetchRecordsCompletionBlock = { records, error in
//...
}

database.add(fetchOperation)
}
}

但是,由于 50 个传入通知中的每一个都是单独的事件,因此该函数会被调用 50 次不同的时间,从而触发大量请求,以使用通知提供的 CKRecordID 获取完整记录我。

如何在合理的时间段内对所有传入通知 CKRecordID 进行排队,以便我可以使用多个 recordID 发出更高效的 CKFetchRecordsOperation 请求一次?

最佳答案

我最终为此使用了一个计时器,而且效果很好。基本上,当新的推送通知到来时,我会启动一个计时器,并且每次收到额外的通知时都会重置它。同时,我收集所有传入的 CKRecordID,然后在计时器触发时处理它们(这发生在通知停止流入之后)。

这是我的代码:

var collectNotificationsTimer: Timer?
var recordIDsFromNotifications = [CKRecordID]()

func processCloudKitNotification(notification: CKNotification, database: CKDatabase){

guard let notification = notification as? CKQueryNotification else { return }
guard let recordID = notification.recordID else { return }

//:: 1 :: Collect record IDs from incoming notifications
if notification.queryNotificationReason == .recordDeleted{
//Delete [-]
//...
}else{
//Add and Edit [+ /]
recordIDsFromNotifications.append(recordID)

//:: 2 :: After collecting IDs for 1 second, request a batch of updated records
collectNotificationsTimer?.invalidate()
collectNotificationsTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false){ _ in

let fetchOperation = CKFetchRecordsOperation(recordIDs: recordIDsFromNotifications)

fetchOperation.fetchRecordsCompletionBlock = { records, error in
recordIDsFromNotifications.removeAll()

if let error = error {
checkCloudKitErrorAndRetryRequest(name: "fetchRecordsCompletionBlock", error: error){}
}else{
if let records = records{
//Save records...
}
}
}
database.add(fetchOperation)
}
}
}

关于swift - 如何对大量入站 CloudKit 通知进行排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51691874/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com