Home / programming / swift / Preparing your SwiftData for CloudKit

Preparing your SwiftData for CloudKit

Things will always change, as of today 27 Dec 2023 it is done this way:

You will need to enable CloudKit for your app and push notifications of course. Cloudkit facilitates sufficient packages to access iCloud for your app. Push notifications facilitate the publisher-subscriber mechanism for your app and server to communicate if there are any changes to your Database. For instance, you make a change on your iPhone, and the similar MacOS app gets notified and updates the Database.

Your Models and Configurations

Your models must conform to the following:

  • You must mark all properties of your model as Optional ‘?’
    • You can give models initial values and not set them as optional
  • You can’t have a ‘.unique’ constraint
  • All relationships must be optional
    Note: iCloud requires all the relationships to provide inverse
    You must tag the other side as inverse and explicitly define them as follows:

One to many:

@Relationship(deleteRule: .nullify, inverse: \ImportedImage.flashcard)
    var importedImage: [ImportedImage]?

other side:

@Relationship
    var flashcard: Flashcard?

Many to many:

@Relationship(deleteRule: .nullify, inverse: \Tag.flashcard)
    var tag: [Tag]?

other side:

@Relationship
    var flashcard: [Flashcard]?

Common errors you will bypass following this guideline:

Failed to find any currently loaded container for model swiftdata
very generic: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1c3c5ca68)
SwiftData/ModelContainer.swift:144: Fatal error: failed to find a currently active container for <ModelName> 
Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *