如果由于网络连接不良而尚未完成创建,如何删除 CKRecord?

How to delete a CKRecord if not yet finished creating due to bad network connection?

我目前正在开发一个 iPhone 应用程序,它利用 CloudKit 在用户设备之间同步应用程序数据。我使用 CoreData 作为我的本地缓存,以确保该应用程序在设备离线时仍然可用。

问题

在开发过程中,我遇到了有关设备离线时同步行为的问题。让我举个例子来解释一下:

  1. 用户创建了一个 Person(我正在处理的一个实体)
  2. 人物保存到本地缓存→CoreData
  3. 创建并设置一个CKRecord来匹配本地缓存实体的数据
  4. 为了将 CKRecord 保存到 CloudKit,将创建一个 CKModifyRecordsOperation 并设置所有需要的完成块和属性
  5. CKModifyRecordsOperation被添加到数据库

如果设备有可用的网络连接,则会根据需要创建 CKRecord。但是,当操作因网络连接不良而失败时,不会创建 CKRecord

假设设备保持离线状态,用户决定再次删除此人。这对于设备本地缓存的数据来说是没有问题的。但是由于本地缓存没有关联CKRecordID,无法创建CKModifyRecordsOperation来删除云端的CKRecord

现在设备已建立网络连接并重新上线。所以现在 CKModifyRecordsOperation 创建 Person-Entity 被执行。这导致本地缓存和云端不同步。

我想通过跟踪与 Person-实体有关的未决操作来解决这个问题。如果此人被删除,则待处理的操作将被取消。

不幸的是我无法得到这个运行。因此,如果我走在正确的轨道上,我将不胜感激!

谢谢!

尝试调整操作的 .qualityOfService 属性。根据位于 https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html#//apple_ref/doc/uid/TP40015243-CH39 的 Apple 文档:

User-interactive: Work that is interacting with the user, such as operating on the main thread, refreshing the user interface, or performing animations. If the work doesn’t happen quickly, the user interface may appear frozen. Focuses on responsiveness and performance. Work is virtually instantaneous.

User-initiated Work that the user has initiated and requires immediate results, such as opening a saved document or performing an action when the user clicks something in the user interface. The work is required in order to continue user interaction. Focuses on responsiveness and performance. Work is nearly instantaneous, such as a few seconds or less.

Utility Work that may take some time to complete and doesn’t require an immediate result, such as downloading or importing data. Utility tasks typically have a progress bar that is visible to the user. Focuses on providing a balance between responsiveness, performance, and energy efficiency. Work takes a few seconds to a few minutes.

Background Work that operates in the background and isn’t visible to the user, such as indexing, synchronizing, and backups. Focuses on energy efficiency. Work takes significant time, such as minutes or hours.

该页面还说默认值介于 user-initiatedUtility 之间。

根据 Apple 开发者论坛 https://forums.developer.apple.com/thread/20047 上的讨论,用户报告未收到离线时失败查询的错误消息,正如您所看到的,这些查询似乎确实存在并再次尝试当连接恢复时。该线程中的用户报告说,将 QoS 参数更改为 User-initiated 会导致在由于没有网络而无法完成操作时立即返回错误。

还显示,当操作被持久化时,操作的 longLivedOperationWasPersistedBlock 将被调用。

因此,选项 1:尝试将操作的 QoS 值调整为 "higher"(更紧急)值,这应该会引发错误,而不是将操作排队等候稍后。

选项 2:尝试添加 longLivedOperationWasPersistedBlock。如果触发,您可以尝试取消该块中的操作,并向用户显示 "no network" 错误。