[SD] 将 SwiftData 与 iCloud 同步
Source: Dev.to
激活 Capability
第一步是激活 iCloud Capability,以同步 SwiftData 与 CloudKit。
在 Xcode 中,在项目 target 的 General 设置附近找到 + Capability 选项。
iCloud 配置
- 活动的服务会显示在 Signing 选项卡中。
- 选择 CloudKit 作为所需的服务。
添加 CloudKit 容器
- 点击 + 按钮添加新的 CloudKit 容器,或选择已有的容器。
- 容器将托管在 Apple 的服务器上,因此需要使用唯一标识符(可以使用 bundle identifier 作为参考)。
- 创建标识符后,点击刷新按钮。
Background Modes
CloudKit 使用远程通知(Remote Notifications)来报告可能在后台发生的数据库更改。
启用 Background Modes Capability,并勾选 Remote Notifications 复选框。
实现限制
- 不能在任何需要同步到 CloudKit 的属性上使用
@Attribute(.unique)。 - 所有属性必须有默认值或标记为可选。
- 所有关系必须标记为可选。
CloudKit 管理
要远程管理 CloudKit 中的数据库,请访问 CloudKit 的 dashboard。
在 dashboard 中,你会看到用于 生产 和 开发 环境的管理面板。
注意
上述所有操作仅在拥有 Apple Developer Program 账户时才可生效。
参考文献
Gauchat, J. D. (2024). SwiftUI for Masterminds: How to take advantage of Swift and SwiftUI to create insanely great apps for iPhones, iPads, and Macs (5ª ed.). John D. Gauchat.