iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🕊️

Using SwiftData with iCloud and App Groups

に公開

SwiftData is a framework available in iOS 17 and later. It is a Core Data-like presence that is designed to work well with SwiftUI.

I recently used it for a personal app with the following configuration:

  • Sync data across multiple devices using iCloud
  • Retrieve data on the widget side using App Groups

Since I couldn't find much good documentation for setting this up, I'll introduce the procedure in this Zenn article.

(PR) Here is the personal app I created!
https://apps.apple.com/jp/app/ドット絵日記-1日1枚ドット絵ၧ記録するダイアリー/id6471673369

SwiftData Crash Course

Here is a brief introduction to SwiftData.

Add @Model to your class.

import Foundation
import SwiftData

@Model
final class Diary {
    var title: String
    var content: String
    var createdAt: Date
    
    init(title: String, content: String, createdAt: Date) {
        self.title = title
        self.content = content
        self.createdAt = createdAt
    }
}

Initialize the container and pass it to modelContainer.

import SwiftUI
import SwiftData

@main
struct SampleApp: App {
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            Diary.self,
        ])
        let modelConfiguration = ModelConfiguration(schema: schema)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
    }
}

Use it from a View as follows:

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    
    // Query
    @Query private var diaries: [Diary]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(diaries) { diary in
                    VStack(alignment: .leading) {
                        Text(diary.title)
                        Text(diary.content)
                        Text(diary.createdAt, format: Date.FormatStyle(date: .numeric, time: .standard))
                    }
                }
            }
            .toolbar {
                ToolbarItem {
                    Button(action: addDiary) {
                        Label("Add", systemImage: "plus")
                    }
                }
            }
        }
    }
    
    // Data addition and persistence
    private func addDiary() {
        let newDiary = Diary(title: "Title",
                             content: "Content",
                             createdAt: .now)
        modelContext.insert(newDiary)
    }
}

This is all you need to read and write data.
Properties in classes with @Model do not need @Published; the View will update automatically when values change.

Supporting iCloud

Creating the Project

Here is how to support iCloud.

When creating a new project, select SwiftData for Storage and check "Host in CloudKit".

Turning on CloudKit

Open the menu from "Xcode Targets > Signing & Capabilities > iCloud" and press the "+" button.
You will be asked for a container identifier; enter a value to set it (it is common practice to start with iCloud.).

It will appear in red immediately after adding, but it will turn to the normal color after a short while.

Click "CloudKit Console" to open it in your browser.

Select CloudKit Database.

A screen like this will appear. We will discuss CloudKit Database later, so let's return to Xcode for now.

Modifying the Entity Definition

One thing to note when using CloudKit is that you must either make properties optional or set default values. Also, attributes like @Attribute(.unique) cannot be used.

Let's fix it while checking the Xcode console errors. In this case, I set default values as follows:

@Model
final class Diary {
    var title: String = ""
    var content: String = ""
    var createdAt: Date = Date.now
    
    // ...
}

Signing in to iCloud and Checking Behavior

Build and check the behavior.

Launch two iPhone simulators and sign in with the same Apple ID. When you add data on one, it will be synchronized on the other.
(On simulators, you might need to switch screens once, but on actual devices, synchronization happens in real-time.)

Supporting App Groups

Creating the Target

Next is supporting App Groups.
First, let's add a Widget to the app.

Add a target via New > Target > Widget Extension.

Turning on App Groups

Add "App Groups" from "Targets > Signing & Capabilities".

Press the "+" button to add an identifier (it is common practice to start with group.).

Also turn on App Groups in the Widget target and check the same group.

Updating Target Membership for Shared Files

Edit the Target Membership of the classes used from the widget side.
(There are probably many other ways to do this, so choose what you prefer.)

First, edit the Entity file.

Since we also want to use the ModelContainer from the widget, move it to a separate file and edit its Target Membership.

// SharedModelContainer.swift
import Foundation
import SwiftData

var sharedModelContainer: ModelContainer = {
    let schema = Schema([
        Diary.self
    ])
    let modelConfiguration = ModelConfiguration(schema: schema)

    do {
        return try ModelContainer(for: schema, configurations: [modelConfiguration])
    } catch {
        fatalError("Could not create ModelContainer: \(error)")
    }
}()

Now it's ready to be called from the widget.

Retrieving Data from SwiftData on the Widget Side

Call the data from the widget.

struct Provider: TimelineProvider {
    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        Task { @MainActor in
            var entries: [SimpleEntry] = []
            
	    // Retrieve data from SwiftData
            let context = sharedModelContainer.mainContext
            let diaries = (try? context.fetch(FetchDescriptor<Diary>())) ?? []
            
            // Add to entries using the retrieved data
        }
    }
}

With this, the main app and the widget can access shared data.

Checking CloudKit Console

I'll also touch upon how to use the CloudKit Console.

Don't Forget to Deploy Scheme Changes on Release

During development, it is connected to the sandbox environment. You need to reflect it to the production environment before release.
You can perform this operation from the "Deploy Scheme Changes..." menu in the CloudKit Console.

The connection destination is specified in the entitlements, so it is also possible to change it to always connect to production.

Add RecordName and Query

If you want to check the data saved in iCloud, an extra step is required.

Select Indexes > Entity and click "Add Basic Index".
Select "recordName" and add it with the Index Type set to "Queryable".

Once added, let's try querying. By default, it's set to write data to the private area, so specify it as follows:

  • DB: "Private Database"
  • Zone: "com.apple.coredata.cloudkit.zone"
  • RECORD_TYPE: The target Type

You can retrieve and display the data as shown in the image.

Only Data Sent to iCloud Will Detect Changes

Changes made to the model class are automatically reflected on the iCloud side.
However, you need to update the model at least once while signed in to iCloud.
Please be careful as simply adding it to the code will not reflect it in iCloud.

Miscellaneous

I'll note down the following limitations I encountered:

  • Enums cannot be used in condition expressions within a Predicate. I handled this by persisting the RawValue instead of the enum.
  • Boolean properties could not be saved to iCloud. The cause is unknown, but I handled it by using strings instead.

Conclusion

I have outlined the steps to make SwiftData compatible with iCloud and App Groups.
I hope this is helpful to someone.

Discussion