Done this model:
@Model
public final class Category: Codable {
var nom: String = ""
@Relationship(deleteRule: .cascade, inverse: \Property.category)
var properties: [Property]?
}
How to create #predicate to search text in like…
let predicate = #Predicate<Category> { category in
searchText.isEmpty || category.nom.localizedStandardContains(searchText) ||
category.properties.contains {
$0.nom.localizedStandardContains(searchText)
}
}
without this error:
SQLCore dispatchRequest: exception handling request: <NSSQLCountRequestContext: 0x6000038dc620>, to-many key not allowed here with userInfo of (null)
CloudKit
RSS for tagStore structured app and user data in iCloud containers that can be shared by all users of your app using CloudKit.
Posts under CloudKit tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hi,
does someone knows about the bug, that the NSPersistentCloudKitContainer doesn't return CKShares at the first time? Is this an intended behavior?
My current fix:
let container: NSPersistentCloudKitContainer = ....
// Fix begin
let managedObject = .... // Object which is in a share
let record = container.record(for: managedObject.objectID)
// Fix end
let shares = (try? container.fetchShares(in: nil)) ?? []
If I execute exactly the same code without the fix that I fetch the record first, then it returns 0 shares. With the fix it is currently 9 shares (the actual count of the shares).
Another fix:
let container: NSPersistentCloudKitContainer = ....
// Fix begin
let _ = try? container.fetchShares(in: nil)
Thread.sleep(forTimeInterval: 0.1)
// Fix end
let shares = (try? container.fetchShares(in: nil)) ?? []
For that fix it also returns at the second time the expected count of shares. But without the delay it returns also at the second time zero shares.
Anyone had the same problem and if so, how do you solve it correctly?
Thanks!
We worked with SwiftData, and once CloudKit was integrated, the synchronization worked well. Even if I rerun the app, it works just as well.
However, when I delete the app and reinstall it, I get a Token Expired error and CloudKit doesn't work properly.
My code is organized like this
public lazy var modelContext: ModelContext = { ModelContext(modelContainer) }()
private lazy var modelContainer: ModelContainer = {
let schema = Schema([
Entity1.self,
Entity2.self,
Entity3.self,
])
let modelConfiguration = ModelConfiguration(
schema: schema,
groupContainer: .identifier("myGroupContainer"),
cloudKitDatabase: .automatic
)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
The error content is as follows
error: CoreData+CloudKit: -[PFCloudKitImportRecordsWorkItem fetchOperationFinishedWithError:completion:]_block_invoke(707): <PFCloudKitImporterZoneChangedWorkItem: 0x3022c0000 - <NSCloudKitMirroringImportRequest: 0x3036e7ac0> 1A7E53D4-E95B-423F-8887-66360F6D8865> {
(
"<CKRecordZoneID: 0x301bb1bf0; zoneName=com.apple.coredata.cloudkit.zone, ownerName=__defaultOwner__>"
)
} - Fetch finished with error:
<CKError 0x301bb5650: "Partial Failure" (2/1011); "Couldn't fetch some items when fetching changes"; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A; container ID = "MyContainerID"; partial errors: {
com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301bb1830: "Change Token Expired" (21/2026); server message = "client knowledge differs from server knowledge"; op = 515034AC3ADC4348; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A>
}>
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1390): <PFCloudKitImporter: 0x3000a1240>: Import failed with error:
<CKError 0x301bb5650: "Partial Failure" (2/1011); "Couldn't fetch some items when fetching changes"; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A; container ID = "MyContainerID"; partial errors: {
com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301bb1830: "Change Token Expired" (21/2026); server message = "client knowledge differs from server knowledge"; op = 515034AC3ADC4348; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A>
}>
Forcing the ModelContainer to be reinitialized fixes the problem,
it's a problem to get this error in the first place,
the error doesn't even go to fatal for me, so I don't even know how to verify that it's happening.
Is there something I'm doing wrong, or do you have any good ideas for solving the same problem?
As of yesterday all queries my app makes to the CloudKit database, and requests via the CloudKit console result in 500 internal errors. We have made no changes to the database or app that could have caused this.
The status page for CloudKit database is green.
Here is a response from the CloudKit console:
{code: 500, message: "internal-error", reason: "Internal error", detailedMessage: undefined, requestUuid: "808955a2-e564-459e-ba9b-1101917ce1a4"}
While Query Record show error:
{
"code": 500,
"message": "internal-error",
"reason": "Internal error",
"requestUuid": "c10d378f-7133-4bea-a40d-d957f80f5de4"
}
Every record type in this container show same error.
But other containers of my apps works will.
I recently converted a Core Data app to use CloudKit. Before the conversion, the sqlite file was around 25MB. After the conversion, the file grew to over one gigabyte. I ran sqlite3_analyzer on the new file and found that a single table, ANSCKRECORDMETADATA, used 95% of the storage, 998MB.
Is this to be expected? I confess that the conversion was a bit bumpy. Maybe I did something to create a monstrosity.
If not expected, should I revert to the old Core Data file, create a new CloudKit container, and repeat the conversion.
My App uses Core Data with Cloudkit when users purchased subscription (and uses only Core Data without subscription). My App should normally appear under 'Settings > [User Name] > iCloud > Apps using iCloud - Show All'; however, some users feedback that they my App cannot access iCloud (a message I displayed in my App when CKContainer.default().accountStatus is NOT available or FileManager.default.ubiquityIdentityToken == nil); and they do not see my App name under 'iCloud > Apps using iCloud - Show All'. From the screenshot that one user provided, only Apps from Apple are displayed under 'Apps using iCloud' and no third-party Apps are shown. Since the user can access to 'iCloud > Apple using iCloud', they have signed in to iCloud successfully. They have also tried to restart my App and restart the phone but the iCloud accessibility issue still remains.
How is it possible that iCloud is accessible only to Apps from Apple but not to third party Apps? What can developer do to resolve iCloud accessibility issue here?
It's 2024, and it still seems like the only sure way to cleanly restart cloud sync on an app using NSPersistentCloudKitContainer is to uninstall and reinstall the app. No need to describe how bad that solution is...
Am I missing something? Is there a better way to safely trigger such a restart of the sync (even if it means losing unsaved data and overwriting with what's in the cloud - which is what a reinstall does anyway)?
I'm trying to integrate the option to the player to save their data in the cloud, I integrate the CloudKit, change some stuff to make it work and build in Xcode to my phone.
But when I try to integrate the CloudSave, 50 unnasigned symbols jump,like this one:
Undefined symbol: _CKContainer_Default
I managed to fix them by updating the recommended settings for Xcode.
But then 4 more errors appear:
Sandbox: il2cpp(12538) deny(1) file-read-data /Users/Username/Test Apple Kit
2022/Build/Il2CppOutputProject/IL2CPP/build/deploy_arm64/il2cpp
So, don't let me build and I've looked everywhere but no one seems to had this same error
Hi,
I'm about to adopt .externalStorage but I will also use CloudKit in the near future. I did not find any reference that list of requirements for SwiftData models to be used with CloudKit, only for Core Data models.
It seems those Core Data requirements (like no-unique) apply to SwiftData as well. However I did not find any info on this:
Can @Attribute(.externalStorage) be used when I want to sync my model with CloudKit?
Hello,
Prior to iOS 17, it was possible to request user discoverability by calling ‚requestApplicationPermission‘. But now it is deprecated. How is the intended way to do this now? How this is for example handled in the Music App? I think this should be a similar approach.
Currently the only option for me seems to save the Email-Address (and maybe phone number) in the CloudKit public database, that other user can discover by this. But that the problem exists, that we need to fetch for changes at phone numbers and mail addresses that are linked to the iCloud account (because user might change anything). Is there a more elegant solution, than just checking the current email addresses and phone numbers at each start of the application (if that is even possible)?
For example the Music App has that Switch "Find my by Apple-ID" but I don't know how this is handled in the background.
Thanks!
When I go to Settings and tap on the account, choose iCloud>manage account storage and try to delete the storage associated with an app id developer mode, it doesn't give me the option to delete the data. I have tried using the CloudKit Console to delete the container data, but the entry for the app is still there. How do I delete it?
SwiftData includes support for CloudKit sync. However, I don't see any way to add conflict resolution behavior. For example, if different devices set different values for a field, or if a relationship is orphaned because of a deletion on another device, the application has to handle this somehow.
In Core Data (which SwiftData wraps), you can handle this with the conflict resolution system (docs) and classes like NSMergePolicy.
Is any of this accessible in SwiftData? If not, how do you deal with conflicts when syncing a SwiftData model with the cloud?
Recently, I have made quite extensive changes to my schema and need to migrate my CoreData + CloudKit model to a new version. The changes require me to use a custom NSEntityMigrationPolicy because I have a rather complex mapping between some old entities and new entities.
I have added a new model version. Deleted some entities, and added some entities.
I have defined the NSEntityMigrationPolicy with createDestinationInstances(forSource:in:manager:) and createRelationships(forDestination:in:manager:).
I have created a new Core Data Mapping Model. This was probably unnecessary.
Within the Core Data Mapping Model, I have specified Custom Policy for all entities.
In my container setup, I added two options, as below:
storeDescription.setOption(false as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption)
storeDescription.setOption(false as NSNumber, forKey: NSInferMappingModelAutomaticallyOption)
I mostly followed a "Core Data Heavyweight Migration" guide. I'm unable to share the link, but it can be quite easily found on the web. (It's not for CloudKit specifically.)
When I run my app, I am getting the most basic of errors, which is:
The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store.
So I guess that migration wasn't even attempted, which makes sense because I set NSMigratePersistentStoresAutomaticallyOption to false.
I tried to go beyond what I could find on the web and attempted to manually initialize migration:
let sourceModel = container.persistentStoreCoordinator.managedObjectModel
guard let modelURL = Bundle.main.url(forResource: "MyModelName", withExtension: "xcdatamodeld") else {
fatalError("Unable to locate model file.")
}
guard let destinationModel = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Unable to load destination model.")
}
let migrationManager = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel)
let mappingModel = NSMappingModel(from: [Bundle.main], forSourceModel: sourceModel, destinationModel: destinationModel)!
migrationManager.currentEntityMapping.entityMigrationPolicyClassName = "MyMigrationPolicyClassName"
I am then stuck at the migrateStore(from:type:mapping:to:type:) method. It seems to target only local storage, not CloudKit. Otherwise, what do I provide for URLs and types?
Any guidance for custom logic CoreData with CloudKit migration would be greatly appreciated.
I have been working on an ios application which I decided to use the new SwiftData architecture, and I now have realized that SwiftData does not support public or shared databases using SwiftData.
I am a new and upcoming Swift developer, who has been self learning the Apple Swift technology. I just learned in this forum that Swift Data does not support Public and Shared Data and I also understand that no plans that have been announced to addressed this feature in the IOS 18 release time frame.
The use case for my application is to implement a social type application, something like applications including X, facebook, etc. These type of applications appear to use Public, Shared and Private data in various existing Apple application.
I would like to complete an application using Swift using ICloud, but I must assume that these current social applications are using other technologies. I am assuming you can do this in Core Data, but my understanding is Apple is asking that we use Swift Data to replace core data. I also am assuming that Swift data is built on core data technology layers. So ... to me it seems hopeful, somehow, to accomplish this using IOS 17 and follow the recommend Swift Data Path.
What are my options for completing these data objectives in IOS? I hope I am addressing these questions in the proper and best forum? Much thanks for any suggestions.
There is no iCloud option in the settings. When I use CloudKit I get
Error synchronizing with cloud for store
Error Domain=SyncedDefaults Code=8888 "No account"
I am following this document from Apple to implement sharing with CloudKit. In it, Apple says
NSPersistentCloudKitContainer uses CloudKit zone sharing to share objects. Each share has its own record zone on the CloudKit server. CloudKit has a limit on how many record zones a database can have.
What is the record zone limit for a private CloudKit database?
I can find information about record and participant limits but not on record zone limits.
How can we identify whether the remote change notification is triggered because some data was changed on a different device and it is downloaded from CloudKit, or it is triggered from the current device because new entity was saved into database.
Because this notification is posted when both remote data is downloaded or local data is created. It would be great if there is a way to understand the origin of the notification.
Has anyone successfully persisted Color, particularly in SwiftData? So far my attempts have failed:
Making Color conform to Codable results in a run time error (from memory something about ColorBox).
Color.Resolved already conforms Codable but this results in "SwiftData/ModelCoders.swift:124: Fatal error: Composite Coder only supports Keyed Container"
None of the other color types conform to Codable (CGColor, NSColor and UIColor) so does the swift language really not have a persistable color type?
CoreData: Zone metadata is missing it's encoded share data but is marked for a mutation: <CKRecordZoneID: 0x600003f044e0; zoneName=com.apple.coredata.cloudkit.share.30BE5FAE-3FE0-4142-90C4-E78FFA90B2A2, ownerName=defaultOwner> - <decode: bad range for [%@] got [offs:312 len:1242 within:0]>