Is it possible to use CloudKit and add integrations, Google Drive for example. If possible, how?
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, "Create a custom data store with SwiftData", and (once updated for API changes since WWDC) that works fine.
However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship?
Here's my code; firstly the cleaned up code from the WWDC session:
import SwiftData
final class JSONStoreConfiguration: DataStoreConfiguration {
typealias Store = JSONStore
var name: String
var schema: Schema?
var fileURL: URL
init(name: String, schema: Schema? = nil, fileURL: URL) {
self.name = name
self.schema = schema
self.fileURL = fileURL
}
static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool {
return lhs.name == rhs.name
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
final class JSONStore: DataStore {
typealias Configuration = JSONStoreConfiguration
typealias Snapshot = DefaultSnapshot
var configuration: JSONStoreConfiguration
var name: String
var schema: Schema
var identifier: String
init(_ configuration: JSONStoreConfiguration, migrationPlan: (any SchemaMigrationPlan.Type)?) throws {
self.configuration = configuration
self.name = configuration.name
self.schema = configuration.schema!
self.identifier = configuration.fileURL.lastPathComponent
}
func save(_ request: DataStoreSaveChangesRequest<DefaultSnapshot>) throws -> DataStoreSaveChangesResult<DefaultSnapshot> {
var remappedIdentifiers = [PersistentIdentifier: PersistentIdentifier]()
var serializedData = try read()
for snapshot in request.inserted {
let permanentIdentifier = try PersistentIdentifier.identifier(for: identifier,
entityName: snapshot.persistentIdentifier.entityName,
primaryKey: UUID())
let permanentSnapshot = snapshot.copy(persistentIdentifier: permanentIdentifier)
serializedData[permanentIdentifier] = permanentSnapshot
remappedIdentifiers[snapshot.persistentIdentifier] = permanentIdentifier
}
for snapshot in request.updated {
serializedData[snapshot.persistentIdentifier] = snapshot
}
for snapshot in request.deleted {
serializedData[snapshot.persistentIdentifier] = nil
}
try write(serializedData)
return DataStoreSaveChangesResult<DefaultSnapshot>(for: self.identifier, remappedIdentifiers: remappedIdentifiers)
}
func fetch<T>(_ request: DataStoreFetchRequest<T>) throws -> DataStoreFetchResult<T, DefaultSnapshot> where T : PersistentModel {
if request.descriptor.predicate != nil {
throw DataStoreError.preferInMemoryFilter
} else if request.descriptor.sortBy.count > 0 {
throw DataStoreError.preferInMemorySort
}
let objs = try read()
let snapshots = objs.values.map({ $0 })
return DataStoreFetchResult(descriptor: request.descriptor, fetchedSnapshots: snapshots, relatedSnapshots: objs)
}
func read() throws -> [PersistentIdentifier : DefaultSnapshot] {
if FileManager.default.fileExists(atPath: configuration.fileURL.path(percentEncoded: false)) {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let data = try decoder.decode([DefaultSnapshot].self, from: try Data(contentsOf: configuration.fileURL))
var result = [PersistentIdentifier: DefaultSnapshot]()
data.forEach { s in
result[s.persistentIdentifier] = s
}
return result
} else {
return [:]
}
}
func write(_ data: [PersistentIdentifier : DefaultSnapshot]) throws {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let jsonData = try encoder.encode(data.values.map({ $0 }))
try jsonData.write(to: configuration.fileURL)
}
}
The data model classes:
import SwiftData
@Model
class Settings {
private(set) var version = 1
@Relationship(deleteRule: .cascade) var hack: Hack? = Hack()
init() {
}
}
@Model
class Hack {
var foo = "Foo"
var bar = 42
init() {
}
}
Container:
lazy var mainContainer: ModelContainer = {
do {
let url = // URL to file
let configuration = JSONStoreConfiguration(name: "Settings", schema: Schema([Settings.self, Hack.self]), fileURL: url)
return try ModelContainer(for: Settings.self, Hack.self, configurations: configuration)
}
catch {
fatalError("Container error: \(error.localizedDescription)")
}
}()
Load function, that saves a new Settings JSON file if there isn't an existing one:
@MainActor func loadSettings() {
let mainContext = mainContainer.mainContext
let descriptor = FetchDescriptor<Settings>()
let settingsArray = try? mainContext.fetch(descriptor)
print("\(settingsArray?.count ?? 0) settings found")
if let settingsArray, let settings = settingsArray.last {
print("Loaded")
} else {
let settings = Settings()
mainContext.insert(settings)
do {
try mainContext.save()
} catch {
print("Error saving settings: \(error)")
}
}
}
The save operation creates a JSON file, which while it isn't a format I would choose, is acceptable, though I notice that the "hack" property (the relationship) doesn't have the correct identifier.
When I run the app again to load the data, I get an error (that there wasn't room to include in this post).
Even if I change Apple's code to not assign a new identifier, so the relationship property and its pointee have the same identifier, it still doesn't load.
Am I doing something obviously wrong, or are relationships not supported in custom data stores?
Using this Apple repository as a basis
https://github.com/apple/sample-cloudkit-zonesharing
I created and verified the shared zone and the same zone is private for the person who shared it and shared for the person who received it, so aren't they the same zones?
[same zone but different id?]
I can make the person who shared the zone (owner) access the zone as a .shared scope just like the person who was shared.
I'm using NSPersistentCloudKitContainer and in the CloudKit dashboards I have added indexes for all my records modifiedTimestamp queryable, modifiedTimestamp sortable and recordName queryable.
But I'm still getting this warning message in the console.
<CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1400): <PFCloudKitImporter: 0x30316c1c0>: Import failed with error:
<CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2312): <NSCloudKitMirroringDelegate: 0x301b1cd20> - Attempting recovery from error: <CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromError:withZoneIDs:forStore:inMonitor:](2622): <NSCloudKitMirroringDelegate: 0x301b1cd20> - Failed to recover from error: CKErrorDomain:12
Recovery encountered the following error: (null):0
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:](612): <NSCloudKitMirroringDelegate: 0x301b1cd20> - resetting internal state after error: <CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2200): <NSCloudKitMirroringDelegate: 0x301b1cd20> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x300738eb0> A3F23AAC-F820-4044-B4B9-28DFAC4DE8D7' due to error: <CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
Hello,
When attempting to create a CKShare on a personal device linked to a Family iCloud plan (non-primary account holder), the operation fails with a quotaExceeded error. This occurs with the Family plan having 1.5TB available storage space.
This is also causing a data loss for the object(s) that were attempted to be shared.
Details
Account Type: Family iCloud Plan (2TB total storage)
Current Family Usage: 399GB
iCloud Account Usage: 70 GB
Steps to Reproduce:
Have an iCloud account with storage over the 5GB free space limit.
Be on a part of a iCloud Family Plan as the non-primary account holder.
Have storage space available in the Family Plan
Attempt to start a CloudKit Share/Collaboration on the device.
Observe that the CKShare creation fails with a quotaExceeded error.
Expected Behavior:
The CKShare should be successfully created, reflecting the total available storage of the Family plan.
Observed Behavior:
The CKShare fails to be created with quotaExceeded.
Additional Testing
On a test device using an iCloud account with no stored data, the CKShare was created successfully and shared without issue.
Suspected Cause
The CKShare functionality is verifying the personal storage allocation of the iCloud account and failing without checking total available storage provided by the Family plan.
I'm having some issues where only a subset of records appear in CloudKit dashboard after I have saved some records in my iOS app using NSPersistentCloudKitContainer. I have noticed that when I'm running my app using the development environment of my CloudKit container everything works smoothly and is uploaded as expected but when I'm using the production environment only a subset of records are actually uploaded.
I'm pulling my hair on how to debug this. -com.apple.CoreData.CloudKitDebug and -com.apple.CoreData.SQLDebug pukes out too much info in the console for me to pinpoint any issue.
Let's say I have a CloudKit database schema where I have records of type Author that are referenced by multiple records of type Article.
I want to delete an Author record if no Article is referencing it. Now consider the following conflict:
device A deleted the last Article referencing Author #42
device B uploads a new Article referencing Author #42 at the same time
The result should be that Author #42 is not deleted after both operations are finished. But both device don't know from each other changes. So either device B could miss that device A deleted the author. Or device A could have missed that a new Article was uploaded and therefore the Author #42 was deleted right after the upload of device B.
I though about using a reference count first. But this won't work if the ref count is part of the Author record. This is because deletions do not use the changeTag to detect lost updates: If device A found a reference count 0 and decides to delete the Author, it might miss that device B incremented the count meanwhile.
I currently see two alternatives:
Using a second record that outlives the Author to keep the reference count and using an atomic operation to update and delete it. So if the update fails, the delete would fail either.
Always adding a new child record to the Author whenever a reference is made. We could call it ReferenceToken. Since child records may not become dangling, CloudKit would stop a deletion, if a new ReferenceToken sets the parent reference to the Author.
Are there any better ways doing this?
I have a simple model
@Model
final class Movie: Identifiable {
#Index\<Movie\>(\[.name\])
var id = UUID()
var name: String
var genre: String?
init(name: String, genre: String?) {
self.name = name
self.genre = genre
}
}
I turned on SQL debugging by including '-com.apple.CoreData.SQLDebug 3' argument on launch.
When I fetch the data using the following code, it selects 3 records initially, but then also selects each record individually even though I am not referencing any other attributes.
var fetchDescriptor = FetchDescriptor\<Movie\>()
fetchDescriptor.propertiesToFetch = \[.id, .name\]
fetchDescriptor.fetchLimit = 3
do {
print("SELECT START")
movies = try modelContext.fetch(fetchDescriptor)
print("SELECT END")
} catch {
print("Failed to load Movie model.")
}
I see it selecting the 3 rows initially, but then it selects each one separately. Why would it do this on the initial fetch? I was hoping to select the data that I want to display and let the system select the entire record only when I access a variable that I did not initially fetch.
CoreData: annotation: fetch using NSSQLiteStatement <0x600002158af0> on entity 'Movie' with sql text 'SELECT 1, t0.Z_PK, t0.ZID, t0.ZNAME FROM ZMOVIE t0 LIMIT 3' returned 3 rows with values: (
"<NSManagedObject: 0x600002158d70> (entity: Movie; id: 0xa583c7ed484691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p1>; data: <fault>)",
"<NSManagedObject: 0x600002158d20> (entity: Movie; id: 0xa583c7ed482691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p2>; data: <fault>)",
"<NSManagedObject: 0x600002158f00> (entity: Movie; id: 0xa583c7ed480691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p3>; data: <fault>)"
)
CoreData: annotation: fetch using NSSQLiteStatement <0x600002154d70> on entity 'Movie' with sql text 'SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZGENRE, t0.ZID, t0.ZNAME FROM ZMOVIE t0 WHERE t0.Z_PK = ? ' returned 1 rows
CoreData: annotation: with values: (
"<NSSQLRow: 0x600000c89500>{Movie 1-1-1 genre=\"Horror\" id=4C5CB4EB-95D7-4DC8-B839-D4F2D2E96ED0 name=\"A000036\" and to-manys=0x0}"
)
This all happens between the SELECT START and SELECT END print statements. Why is it fulfilling the faults immediately?
Is it ok to have latency about 4 sec? The amount of downloaded data is less than 1 MB. Maybe I need to setup an index for every field requested?
Hello everyone,
I'm trying to adopt the new Staged Migrations for Core Data and I keep running into an error that I haven't been able to resolve.
The error messages are as follows:
warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Movie' so +entity is unable to disambiguate.
warning: 'Movie' (0x60000350d6b0) from NSManagedObjectModel (0x60000213a8a0) claims 'Movie'.
error: +[Movie entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
This happens for all of my entities when they are added/fetched. Movie is an abstract entity subclass, and it has the error error: +[Movie entity] Failed to find which is unique to the subclass entities, but this occurs for all entities.
The NSPersistentContainer is loaded only once, and I set the following option after it's loaded:
storeDescription.setOption(
[stages],
forKey: NSPersistentStoreStagedMigrationManagerOptionKey
)
The warnings and errors only appear after I fetch or save to context. It happens regardless of whether the database was migrated or not. In my test project, using the generic NSManagedObject with NSEntityDescription.insertNewObject(forEntityName: "MyEntity", into: context) does not cause the issue. However, using the generic NSManagedObject is not a viable option for my app.
Setting the module to "Current Project Module" doesn't change anything, except that it now prints "claims 'MyModule.Show'" in the warnings. I have verified that there are no other entities with the same name or renameIdentifier.
Has anyone else encountered this issue, or can offer any suggestions on how to resolve it?
Thanks in advance for any help!
Hello,
I have a problem with SwiftData and Predicates that check for the persistentModelID of the relations.
My data model looks simplified like this:
Day -> TimeEntry[] -> Hashtag[]
What I want to achieve is to query the days and associated time entries via assigned tags.
This is my predicate:
let identifier = filterHashtags.map(\.persistentModelID)
...
#Predicate<TimeEntry> { timeEntry in
identifiers.count == timeEntry.tags.filter { tag in
identifiers.contains(tag.persistentModelID)
}.count
}
It does not return any data when I check for the persistentModelID. However, if I use another property of the tags, e.g. the name or a generated UUID for the check, the predicate works. Is this a general problem with PersistentIdentifier in Predicates or am I missing something?
Thanks in advance
Are there any differences (either performance or memory considerations) between removing an array of model objects directly using .removeAll() vs using modelContext? Or, are they identical?
Attached below is an example to better illustrate the question (i.e., First Way vs Second Way)
// Model Definition
@Model
class GroupOfPeople {
let groupName: String
@Relationship(deleteRule: .cascade, inverse: \Person.group)
var people: [Person] = []
init() { ... }
}
@Model
class Person {
let name: String
var group: GroupOfPeople?
init() { ... }
}
// First way
struct DemoView: View {
@Query private groups: [GroupOfPeople]
var body: some View {
List(groups) { group in
DetailView(group: group)
}
}
}
struct DetailView: View {
let group: GroupOfPeople
var body: some View {
Button("Delete All Participants") {
group.people.removeAll()
}
}
// Second way
struct DemoView: View {
@Query private groups: [GroupOfPeople]
var body: some View {
List(groups) { group in
DetailView(group: group)
}
}
}
struct DetailView: View {
@Environment(\.modelContext) private var context
let group: GroupOfPeople
var body: some View {
Button("Delete All Participants") {
context.delete(model: Person.self, where: #Predicate { $0.group.name == group.name })
} // assuming group names are unique. more of making a point using modelContext instead
}
I have a simple app that makes an HTTPS call to gather some JSON which I then parse and add to my SwiftData database. The app then uses a simple @Query in a view to get the data into a list.
on iOS 16 this works fine. No problems. But the same code on iOS 26 (targeting iOS 18.5) crashes after about 15 seconds of idle time after the list is populated. The error message is:
Could not cast value of type '__NSCFNumber' (0x1f31ee568) to 'NSString' (0x1f31ec718).
and occurs when trying to access ANY property of the list.
I have a stripped down version of the app that shows the crash available.
To replicate the issue:
open the project in Xcode 26
target any iOS 26 device or simulator
compile and run the project.
after the list is displayed, wait about 15 seconds and the app crashes.
It is also of note that if you try to run the app again, it will crash immediately, unless you delete the app from the device.
Any help on this would be appreciated.
Feedback number FB20295815 includes .zip file
Below is the basic code (without the data models)
The Best Seller List.Swift
import SwiftUI
import SwiftData
@main
struct Best_Seller_ListApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer (for: NYTOverviewResponse.self)
}
}
ContentView.Swift
import os.log
import SwiftUI
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@State private var listEncodedName = String()
var body: some View {
NavigationStack () {
ListsView()
}
.task {
await getBestSellerLists()
}
}
func getBestSellerLists() async {
guard let url = URL(string: "https://api.nytimes.com/svc/books/v3/lists/overview.json?api-key=\(NYT_API_KEY)") else {
Logger.errorLog.error("Invalid URL")
return
}
do {
let decoder = JSONDecoder()
var decodedResponse = NYTOverviewResponse()
//decode the JSON
let (data, _) = try await URLSession.shared.data(from: url)
decoder.keyDecodingStrategy = .convertFromSnakeCase
decodedResponse = try decoder.decode(NYTOverviewResponse.self, from: data)
//remove any lists that don't have list_name_encoded. Fixes a bug in the data
decodedResponse.results!.lists = decodedResponse.results!.lists!.filter { $0.listNameEncoded != "" }
// sort the lists
decodedResponse.results!.lists!.sort { (lhs, rhs) -> Bool in
lhs.displayName < rhs.displayName
}
//delete any potential existing data
try modelContext.delete(model: NYTOverviewResponse.self)
//add the new data
modelContext.insert(decodedResponse)
} catch {
Logger.errorLog.error("\(error.localizedDescription)")
}
}
}
ListsView.Swift
import os.log
import SwiftData
import SwiftUI
@MainActor
struct ListsView: View {
//MARK: - Variables and Constants
@Query var nytOverviewResponses: [NYTOverviewResponse]
enum Updated: String {
case weekly = "WEEKLY"
case monthly = "MONTHLY"
}
//MARK: - Main View
var body: some View {
List {
if nytOverviewResponses.isEmpty {
ContentUnavailableView("No lists yet", systemImage: "list.bullet", description: Text("NYT Bestseller lists not downloaded yet"))
} else {
WeeklySection
MonthlySection
}
}
.navigationBarTitle("Bestseller Lists", displayMode: .large)
.listStyle(.grouped)
}
var WeeklySection: some View {
let rawLists = nytOverviewResponses.last?.results?.lists ?? []
// Build a value-typed array to avoid SwiftData faulting during sort
let weekly = rawLists
.filter { $0.updateFrequency == Updated.weekly.rawValue }
.map { (name: $0.displayName, encoded: $0.listNameEncoded, model: $0) }
.sorted { $0.name < $1.name }
return Section(header: Text("Weekly lists to be published on \(nytOverviewResponses.last?.results?.publishedDate ?? "-")")) {
ForEach(weekly, id: \.encoded) { item in
Text(item.name).font(Font.custom("Georgia", size: 17))
}
}
}
var MonthlySection: some View {
let rawLists = nytOverviewResponses.last?.results?.lists ?? []
// Build a value-typed array to avoid SwiftData faulting during sort
let monthly = rawLists
.filter { $0.updateFrequency == Updated.monthly.rawValue }
.map { (name: $0.displayName, encoded: $0.listNameEncoded, model: $0) }
.sorted { $0.name < $1.name }
return Section(header: Text("Monthly lists to be published on \(nytOverviewResponses.last?.results?.publishedDate ?? "-")")) {
ForEach(monthly, id: \.encoded) { item in
Text(item.name).font(Font.custom("Georgia", size: 17))
}
}
}
}
Document based SwiftData apps do not autosave changes to the ModelContext at all. This issue has been around since the first release of this SwiftData feature.
In fact, the Apple WWDC sample project (https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata) does not persist any data in its current state, unless one inserts modelContext.save() calls after every data change.
I have reported this under the feedback ID FB16503154, as it seemed to me that there is no feedback report about the fundamental issue yet.
Other posts related to this problem:
https://forums.developer.apple.com/forums/thread/757172
https://forums.developer.apple.com/forums/thread/768906
https://developer.apple.com/forums/thread/764189
"No records found"
If I create a new record on the console, I can copy the record name.
I can then query for recordName and get that individual record back.
BUT no other queries work. I cannot query all records. I cannot query by individual property.
Just returns "no records found"
Seems like my indexes got messed up. Is there a way to reset indexes on prod?
This is on a coredata.cloudkit managed zone.
throughout all of Foundation's URL documentation, its called out in multiple places that data stored inside an app sandox's caches directory doesn't count towards data and documents usage in the settings app
but in practice, it looks like storing data there does in fact count towards documents & data for the app
i'm trying to understand if the docs are wrong, if theres a bug in the settings app, or if this is a mistake on my part
I have a SwiftData model where I need to customize behavior based on the value of a property (connectorType). Here’s a simplified version of my model:
@Model
public final class ConnectorModel {
public var connectorType: String
...
func doSomethingDifferentForEveryConnectorType() {
...
}
}
I’d like to implement doSomethingDifferentForEveryConnectorType in a way that allows the behavior to vary depending on connectorType, and I want to follow best practices for scalability and maintainability. I’ve come up with three potential solutions, each with pros and cons, and I’d love to hear your thoughts on which one makes the most sense or if there’s a better approach:
**Option 1: Use switch Statements
**
func doSomethingDifferentForEveryConnectorType() {
switch connectorType {
case "HTTP":
// HTTP-specific logic
case "WebSocket":
// WebSocket-specific logic
default:
// Fallback logic
}
}
Pros: Simple to implement and keeps the SwiftData model observable by SwiftUI without any additional wrapping.
Cons: If more behaviors or methods are added, the code could become messy and harder to maintain.
**Option 2: Use a Wrapper with Inheritance around swiftdata model
**
@Observable
class ParentConnector {
var connectorModel: ConnectorModel
init(connectorModel: ConnectorModel) {
self.connectorModel = connectorModel
}
func doSomethingDifferentForEveryConnectorType() {
fatalError("Not implemented")
}
}
@Observable
class HTTPConnector: ParentConnector {
override func doSomethingDifferentForEveryConnectorType() {
// HTTP-specific logic
}
}
Pros: Logic for each connector type is cleanly organized in subclasses, making it easy to extend and maintain.
Cons: Requires introducing additional observable classes, which could add unnecessary complexity.
**Option 3: Use a @Transient class that customizes behavior
**
protocol ConnectorProtocol {
func doSomethingDifferentForEveryConnectorType(connectorModel: ConnectorModel)
}
class HTTPConnectorImplementation: ConnectorProtocol {
func doSomethingDifferentForEveryConnectorType(connectorModel: ConnectorModel) {
// HTTP-specific logic
}
}
Then add this to the model:
@Model
public final class ConnectorModel {
public var connectorType: String
@Transient
public var connectorImplementation: ConnectorProtocol?
// Or alternatively from swiftui I could call myModel.connectorImplementation.doSomethingDifferentForEveryConnectorType() to avoid this wrapper
func doSomethingDifferentForEveryConnectorType() {
connectorImplementation?.doSomethingDifferentForEveryConnectorType(connectorModel: self)
}
}
Pros: Decouples model logic from connector-specific behavior. Avoids creating additional observable classes and allows for easy extension.
Cons: Requires explicitly passing the model to the protocol implementation, and setup for determining the correct implementation needs to be handled elsewhere.
My Questions
Which approach aligns best with SwiftData and SwiftUI best practices, especially for scalable and maintainable apps?
Are there better alternatives that I haven’t considered?
If Option 3 (protocol with dependency injection) is preferred, what’s the best way to a)manage the transient property 2) set the correct implementation and 3) pass reference to swiftdata model?
Thanks in advance for your advice!
I have encountered an issue with a customer’s data access after they migrated to a different iCloud account, and I’m looking for guidance.
The Situation:
The customer was logged into their account on my app, which was associated with a specific iCloud account (iCloud A).
They had all their app data available while using iCloud A.
The customer then switched to a new iCloud account (iCloud B) on the same device, while still using the same app account.
After switching iCloud accounts, their data is no longer visible in the app or my CloudKit dashboard.
My Investigation:
I accessed the customer’s CloudKit data via the CloudKit Console, acting as their iCloud account.
I couldn’t find the private database zone or any of their records when accessing iCloud A through the console.
I don’t believe the data was deleted since actions performed under iCloud B shouldn’t affect data stored in iCloud A.
My Hypothesis:
I suspect that the customer’s old iCloud account (iCloud A) may have downgraded or stopped paying for iCloud storage.
If the iCloud subscription is inactive or expired, could that prevent me from accessing their CloudKit data?
Would renewing the iCloud subscription for iCloud A restore access to the missing data?
Questions:
Does an unpaid or expired iCloud account restrict access to CloudKit records, even if they weren’t deleted?
Would paying for iCloud storage again restore the data previously stored in CloudKit?
Is there any way to recover the customer’s CloudKit data if they are unable to access their old iCloud account?
If anyone has a simpler approach to recovering the customer’s iCloud-stored app data or has experience dealing with iCloud migrations like this, I’d appreciate your insights. Thank you in advance for any advice!
I am following Apple's instruction to sync SwiftData with CloudKit. While initiating the ModelContainer, right after removing the store from Core Data, the error occurs:
FAULT: NSInternalInconsistencyException: This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.; (user info absent)
I've tried removing default.store and its related files/folders before creating the ModelContainer with FileManager but it does not resolve the issue. Isn't it supposed to create a new store when the ModelContainer is initialized? I don't understand why this error occurs. Error disappears when I comment out the #if DEBUG block.
Code:
import CoreData
import SwiftData
import SwiftUI
struct InitView: View {
@Binding var modelContainer: ModelContainer?
@Binding var isReady: Bool
@State private var loadingDots = ""
@State private var timer: Timer?
var body: some View {
VStack(spacing: 16) {
Text("Loading\(loadingDots)")
.font(.title2)
.foregroundColor(.gray)
}
.padding()
.onAppear {
startAnimation()
registerTransformers()
let config = ModelConfiguration()
let newContainer: ModelContainer
do {
#if DEBUG
// Use an autorelease pool to make sure Swift deallocates the persistent
// container before setting up the SwiftData stack.
try autoreleasepool {
let desc = NSPersistentStoreDescription(url: config.url)
let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.my-container-identifier")
desc.cloudKitContainerOptions = opts
// Load the store synchronously so it completes before initializing the
// CloudKit schema.
desc.shouldAddStoreAsynchronously = false
if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Page.self]) {
let container = NSPersistentCloudKitContainer(name: "Pages", managedObjectModel: mom)
container.persistentStoreDescriptions = [desc]
container.loadPersistentStores { _, err in
if let err {
fatalError(err.localizedDescription)
}
}
// Initialize the CloudKit schema after the store finishes loading.
try container.initializeCloudKitSchema()
// Remove and unload the store from the persistent container.
if let store = container.persistentStoreCoordinator.persistentStores.first {
try container.persistentStoreCoordinator.remove(store)
}
}
// let fileManager = FileManager.default
// let sqliteURL = config.url
// let urls: [URL] = [
// sqliteURL,
// sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-shm"),
// sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-wal"),
// sqliteURL.deletingLastPathComponent().appendingPathComponent(".default_SUPPORT"),
// sqliteURL.deletingLastPathComponent().appendingPathComponent("default_ckAssets")
// ]
// for url in urls {
// try? fileManager.removeItem(at: url)
// }
}
#endif
newContainer = try ModelContainer(for: Page.self,
configurations: config) // ERROR!!!
} catch {
fatalError(error.localizedDescription)
}
modelContainer = newContainer
isReady = true
}
.onDisappear {
stopAnimation()
}
}
private func startAnimation() {
timer = Timer.scheduledTimer(
withTimeInterval: 0.5,
repeats: true
) { _ in
updateLoadingDots()
}
}
private func stopAnimation() {
timer?.invalidate()
timer = nil
}
private func updateLoadingDots() {
if loadingDots.count > 2 {
loadingDots = ""
} else {
loadingDots += "."
}
}
}
import CoreData
import SwiftData
import SwiftUI
@main
struct MyApp: App {
@State private var modelContainer: ModelContainer?
@State private var isReady: Bool = false
var body: some Scene {
WindowGroup {
if isReady, let modelContainer = modelContainer {
ContentView()
.modelContainer(modelContainer)
} else {
InitView(modelContainer: $modelContainer, isReady: $isReady)
}
}
}
}
I have this actor
actor ConcurrentDatabase: ModelActor {
nonisolated let modelExecutor: any ModelExecutor
nonisolated let modelContainer: ModelContainer
init(modelContainer: ModelContainer) {
self.modelExecutor = DefaultSerialModelExecutor(modelContext: ModelContext(modelContainer))
self.modelContainer = modelContainer
}
/// Save pending changes in the model context.
private func save() {
if self.modelContext.hasChanges {
do {
try self.modelContext.save()
} catch {
...
}
}
}
}
I am getting a runtime crash on:
try self.modelContext.save()
when trying to insert something into the database and save
Thread 1: Fatal error: Incorrect actor executor assumption; Expected same executor as MainActor.
Can anyone explain why this is happening?