iOS 13から導入されたCoreDataとCloudKitの自動連携を試してみた。
目次
Xcodeの設定
以下の公式ドキュメントがとても参考になった。
以下の通り、iCloud, CloudKit, push notifications, remote notificationsをオンにする。
(私はremote notificationsをオンにするのを忘れたため、Cloud連携がうまく動かなかったことがある。)
First, enable iCloud, CloudKit, push notifications, and remote notifications in the background as described in the preceeding sections. Then, replace your persistent container with an instance of
NSPersistent
.Cloud Kit Container
記事の「Manage Multiple Source」のコードは複数のストアを管理する場合に必要な方法で今回は必要ない。
Persistence.swiftは以下の通り。
プロジェクト作成時に「Host in Cloudkit」にチェックをすればそのままいじる必要はないです。
let container: NSPersistentCloudKitContainer init(inMemory: Bool = false) { container = NSPersistentCloudKitContainer(name: "Hogehoge") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) }
CapabilityでCloudKitにチェックをつける。

赤文字のContainersは自分で追加した。
+ボタンの後に、バンドルIDを入力するとiCloud.が先頭に自動的に追加されてコンテナが作成される。
ここで一度アプリをiPhoneで実行、適当にデータを追加してみた。
CloudKit DashBoardについて
次に、上図の少し下の方に「CloudKit DashBoard」ボタンがあるのでブラウザで飛ぶ。
「Schema」の「Record Types」にXcodeのモデルエディタで作ったエンティティがあって少し感動。

「Data」の「Records」でQuery Recordsをするとエラーが発生。
“Field ‘recordName’ is not marked queryable”
https://lyons.app/2021/07/05/how-to-fix-field-recordname-is-not-marked-queryable-in-cloudkit/
上のブログに解決方法が書いてあった。
SchemaでIndexesでIndexを1つ追加する必要があるらしい。(何故だ。)

「recordName」+「QUERYABLE」を追加。
「Data」の「Records」でQuery Recordsを実行。

(PrivateDatabase、com.apple.coredata..、レコードタイプは変更した。)
アプリで追加したデータが表示された!
AppStoreにリリースしたアプリではDevelopmentは使えない
Xcodeで動かしたアプリではうまく動作したのに、AppStoreにリリースしたアプリでうまく連携できないことがあった。
Apps in the App Store can access only the production environment.
Developmentは開発用のクラウドなので、AppStoreにリリースしたアプリでは使えないようだ。
AppStoreに出す前には忘れずにDeployしよう。
あとは、AppleIDが同一でないとデータの同期はされないので注意しましょう。
Udemy
Udemyでも無料で解説していますので宜しければどうぞ。
https://www.udemy.com/course/swiftui-coredata-todo/learn/lecture/30398486#overview