iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

error sharing url on cloudkit share
I'm studying sharing through this link. I followed the first steps by changing the bundle identifier of the project, the tests and placing my own container in the config and in the info.plist. https://github.com/apple/sample-cloudkit-zonesharing The app appears and in the log it appears that it has managed to access my iCloud, but when I click on share and share something, the following message appears in the console, on the simulator and on the iPhone: "No options were found, providing default value for access type" "No options were found, providing default values ​​for permissions" "connection invalidated" And finally, when I click on the shared link, the following message appears: "Item unavailable The owner stopped sharing, or you don't have permission to open it."
0
0
565
Sep ’24
Jak usunąć zakładkę Uaktualnienia Beta z urządzeń?
Witam, na każdym urządzeniu Apple, iPhone’a/Watch mam możliwość instalować wersje beta developer. chciałbym wypisać się z wersji beta developer - nie mieć ich w ustawieniach. wiem że beta developer jest przypisana do mojego konta iCloud. po wylogowaniu się i przywróceniu ustawień fabrycznych, zakładka znika. gdy loguje się na konto iCloud pojawia Się wszędzie. nie zapisałem sie do developer bety. jak to usunąc?
1
0
773
Dec ’24
Core Data, Swift 6, Concurrency and more
I have the following struct doing some simple tasks, running a network request and then saving items to Core Data. Per Xcode 26's new default settings (onisolated(nonsending) & defaultIsolation set to MainActor), the struct and its functions run on the main actor, which works fine and I can even safely omit the context.perform call because of it, which is great. struct DataHandler { func importGames(withIDs ids: [Int]) async throws { ... let context = PersistenceController.shared.container.viewContext for game in games { let newGame = GYGame(context: context) newGame.id = UUID() } try context.save() } } Now, I want to run this in a background thread to increase performance and responsiveness. So I followed this session (https://developer.apple.com/videos/play/wwdc2025/270) and believe the solution is to mark the struct as nonisolated and the function itself as @concurrent. The function now works on a background thread, but I receive a crash: _dispatch_assert_queue_fail. This happens whether I wrap the Core Data calls with context.perform or not. Alongside that I get a few new warnings which I have no idea how to work around. So, what am I doing wrong here? What's the correct way to solve this simple use case with Swift 6's new concurrency stuff and the default main actor isolation in Xcode 26? Curiously enough, when setting onisolated(nonsending) to false & defaultIsolation to non isolating, mimicking the previous behavior, the function works without crashing. nonisolated struct DataHandler { @concurrent func importGames(withIDs ids: [Int]) async throws { ... let context = await PersistenceController.shared.container.newBackgroundContext() for game in games { let newGame = GYGame(context: context) newGame.id = UUID() // Main actor-isolated property 'id' can not be mutated from a nonisolated context; this is an error in the Swift 6 language mode } try context.save() } }
2
0
108
Jun ’25
Invalid bundle ID for container
Hi. I am having this error when trying to write to CloudKit public database. <CKError 0x600000dbc4e0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; On app launch, I check for account status and ensure that the correct bundle identifier and container is being used. When the account status is checked, I do get the correct bundle id and container id printed in the console but trying to read or write to the container would throw that "Invalid bundle ID for container" error. private init() { container = CKContainer.default() publicDB = container.publicCloudDatabase // Check iCloud account status checkAccountStatus() } func checkAccountStatus() { print("🔍 CloudKit Debug:") print("🔍 Bundle identifier from app: (Bundle.main.bundleIdentifier ?? "unknown")") print("🔍 Container identifier: (container.containerIdentifier ?? "unknown")") container.accountStatus { [weak self] status, error in DispatchQueue.main.async { switch status { case .available: self?.isSignedIn = true self?.fetchUserID() case .noAccount, .restricted, .couldNotDetermine: self?.isSignedIn = false self?.errorMessage = "Please sign in to iCloud in Settings to use this app." default: self?.isSignedIn = false self?.errorMessage = "Unknown iCloud account status." } print("User is signed into iCloud: \(self?.isSignedIn ?? false)") print("Account status: \(status.rawValue)") } } } I have tried: Creating a new container Unselecting and selecting the container in signing & capabilities Unselecting and selecting the container in App ID Configuration I used to have swift data models in my code and read that swift data is not compatible with CloudKit public data so I removed all the models and any swift data codes and only uses CloudKit public database. let savedRecord = try await publicDB.save(record) Nothing seems to work. If anyone could help please? Rgds, Hans
1
0
152
Jun ’25
Display name for CloudKit container in the "Manage Storage" view of Settings
How can I set the display name of the CloudKit container in Settings -> iCloud -> Manage Storage. I have multiple containers, some legacy, and some for certain modules that are shared among a suite of apps. The problem is all Containers show the same name so it is not possible to advise a user which containers are safe to delete. I am using NSPersistentCloudKitContainer.
1
0
269
Nov ’24
Recovering Customer's Data After iCloud Migration
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!
2
0
802
Jan ’25
Avoiding deletion of referenced records
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?
0
0
423
Nov ’24
Mixing in-memory and persistent SwiftData containers in a Document-based App?
Hello, I'm trying to work on an iPadOS and macOS app that will rely on the document-based system to create some kind of orientation task to follow. Let say task1.myfile will be a check point regulation from NYC to SF and task2.myfile will be a visit as many key location as you can in SF. The file represent the specific landmark location and rules of the game. And once open, I will be able to read KML/GPS file to evaluate their score based with the current task. But opened GPS files does not have to be stored in the task file itself, it stay alongside. I wanted to use that scenario to experiment with SwiftData (I'm a long time CoreData user, I even wrote my own WebDAV based persistent store back in the day), and so, mix both on file and in memory persistent store, with distribution based on object class. With CoreData it would have been possible, but I do not see how to achieve that with SwiftData and DocumentGroup integration. Any idea how to do that?
1
0
99
Aug ’25
SiftData with CloudKit testing
I'm trying to add Cloud Kit integration to SwiftData app (that is already in the App Store, btw). When the app is installed on devices that are directly connected to Xcode, it works (a bit slow, but pretty well). But when the app is distributed to Testflight internal testers, the synchronization doesn't happen at all. So, is this situation normal and how can I test apps with iCloud integration properly?
2
0
352
Nov ’24
Crash with NSAttributedString in Core Data
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted: CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Here's the code that tries to save the attributed string: struct AttributedDetailView: View { @ObservedObject var item: Item @State private var notesText = AttributedString() var body: some View { VStack { TextEditor(text: $notesText) .padding() .onChange(of: notesText) { item.attributedString = NSAttributedString(notesText) } } .onAppear { if let nsattributed = item.attributedString { notesText = AttributedString(nsattributed) } else { notesText = "" } } .task { item.attributedString = NSAttributedString(notesText) do { try item.managedObjectContext?.save() } catch { print("core data save error = \(error)") } } } } This is the attribute setup in the Core Data model editor: Is there a workaround for this? I filed FB17943846 if someone can take a look. Thanks.
2
0
169
Jun ’25
How to completely reset SwiftData?
Is it possible to reset SwiftData to a state identical to that of a newly installed app? I have experienced some migration issues where, when I add a new model, I need to reinstall the entire application for the ModelContainer creation to work. Deleting all existing models does not seem to make any difference. A potential solution I currently have, which appears to work but feels quite hacky, is as follows: let _ = try! ModelContainer() modelContainer = try! ModelContainer(for: Student.self, ...) This seems to force out this error CoreData: error: Error: Persistent History (66) has to be truncated due to the following entities being removed: (...) which seems to reset SwiftData. Any other suggestions?
2
0
598
Nov ’24
'NSInvalidArgumentException', reason: 'Duplicate version checksums across stages detected.'
I have an iOS app using SwiftData with VersionedSchema. The schema is synchronized with an CloudKit container. I previously introduced some model properties that I have now removed, as they are no longer needed. This results in the current schema version being identical to one of the previous ones (except for its version number). This results in the following exception: 'NSInvalidArgumentException', reason: 'Duplicate version checksums across stages detected.' So it looks like we cannot have a newer schema version with an identical content to an older schema version. The intuitive way would be to re-add the old (identical) schema version to the end of the "schemas" list property in the SchemaMigrationPlan, in order to signal that it is the newest one, and to add a migration stage back to it, thus: public enum MySchemaMigrationPlan: SchemaMigrationPlan { public static var schemas: [any VersionedSchema.Type] { [ SchemaV100.self, SchemaV101.self, SchemaV100.self ] } public static var stages: [MigrationStage] { [ migrateV100toV101, migrateV101toV100 ] } However, I am not sure if this is the right way to go, as previously, as I wanted to write unit tests for schema migration and rollback, I tried defining an inverse for each migration stage, so that I could trigger a migration and a rollback from a unit test, which resulted in an exception saying that it is not supported to downgrade a VersionedSchema. I must admit that I solved the original problem by introducing a dummy model property that I will later remove. What would have been the correct approach?
1
0
85
Jun ’25
CloudKit + SwifData setup
Hey folks, I'm having an issue where iCloud sync is only working in the Development environment, not on Prod. I have deployed the schema to Prod through the CloudKit console, although I did it after the app went live on the AppStore. Even though the two schema are identical, iCloud sync just doesn't work on Prod. Things I tried on the code side: Initially I did the most basic SwiftData+CloudKit setup: var modelContainer: ModelContainer { let schema = Schema([Book.self, Goal.self]) let config = ModelConfiguration(isStoredInMemoryOnly: false, cloudKitDatabase: doesUserSyncToiCloud ? .automatic : .none) var container: ModelContainer do { container = try ModelContainer(for: schema, configurations: config) } catch { fatalError() } return container } var body: some Scene { WindowGroup { AnimatedSplashScreen { MainTabView() } } .modelContainer(modelContainer) } This is enough to make iCloud sync work at the Development level. Then when I noticed the issues on Prod I did some digging and found this on the Docs (https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices): let config = ModelConfiguration() 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.com.example.Trips") desc.cloudKitContainerOptions = opts // Load the store synchronously so it completes before initializing the // CloudKit schema. desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Trip.self, Accommodation.self]) { let container = NSPersistentCloudKitContainer(name: "Trips", 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) } } } #endif modelContainer = try ModelContainer(for: Trip.self, Accommodation.self, configurations: config) } catch { fatalError(error.localizedDescription) } I've no idea why Apple would include this CoreData setup in a SwiftData documentation, but I went ahead and adapted it to my code as well. I see now that some new "assets" were added to my Development schema, but I'm afraid to deploy these changes to Prod, since I'm not even confident that this CoreData setup is necessary in a SwiftData app. Does anyone have any thoughts on this? Have you run into similar issues? Any help would be much appreciated; thanks!
0
0
356
Nov ’24
SwiftData 100% crash when fetching history with codable (test included!)
SwiftData crashes 100% when fetching history of a model that contains an optional codable property that's updated: SwiftData/Schema.swift:389: Fatal error: Failed to materialize a keypath for someCodableID.someID from CrashModel. It is possible that this path traverses a type that does not work with append(), please file a bug report with a test. Would really appreciate some help or even a workaround. Code: import Foundation import SwiftData import Testing struct VaultsSwiftDataKnownIssuesTests { @Test func testCodableCrashInHistoryFetch() async throws { let container = try ModelContainer( for: CrashModel.self, configurations: .init( isStoredInMemoryOnly: true ) ) let context = ModelContext(container) try SimpleHistoryChecker.hasLocalHistoryChanges(context: context) // 1: insert a new value and save let model = CrashModel() model.someCodableID = SomeCodableID(someID: "testid1") context.insert(model) try context.save() // 2: check history it's fine. try SimpleHistoryChecker.hasLocalHistoryChanges(context: context) // 3: update the inserted value before then save model.someCodableID = SomeCodableID(someID: "testid2") try context.save() // The next check will always crash on fetchHistory with this error: /* SwiftData/Schema.swift:389: Fatal error: Failed to materialize a keypath for someCodableID.someID from CrashModel. It is possible that this path traverses a type that does not work with append(), please file a bug report with a test. */ try SimpleHistoryChecker.hasLocalHistoryChanges(context: context) } } @Model final class CrashModel { // optional codable crashes. var someCodableID: SomeCodableID? // these actually work: //var someCodableID: SomeCodableID //var someCodableID: [SomeCodableID] init() {} } public struct SomeCodableID: Codable { public let someID: String } final class SimpleHistoryChecker { static func hasLocalHistoryChanges(context: ModelContext) throws { let descriptor = HistoryDescriptor<DefaultHistoryTransaction>() let history = try context.fetchHistory(descriptor) guard let last = history.last else { return } print(last) } }
0
0
62
May ’25
Using relationships in SortDescriptor crashing on release
If use a SortDescriptor for a model and sort by some attribute from a relationship, in DEBUG mode it all works fine and sorts. However, in release mode, it is an instant crash. SortDescriptor(.name, order: .reverse) ---- works SortDescriptor(.assignedUser?.name, order: .reverse) ---- works in debug but crash in release. What is the issue here, is it that SwiftData just incompetent to do this?
2
0
82
Aug ’25
Debugging/Fixing deleted relationship objects with SwiftData
Using SwiftData and this is the simplest example I could boil down: @Model final class Item { var timestamp: Date var tag: Tag? init(timestamp: Date) { self.timestamp = timestamp } } @Model final class Tag { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } Notice Tag has no reference to Item. So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors: SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation) I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item references to that tag when a Tag is deleted. But, the damage is already done. How can I iterate through all Items that referenced a deleted tag and set them to nil or to a placeholder Tag? Or how can I catch that error and fix it when it comes up? The crash doesn't occur when loading an Item, only when accessing item.tag?.timestamp, in fact, item.tag?.id is still ok and doesn't crash since it doesn't have to load the backing data. I've tried things like just looping through all items and setting tag to nil, but saving the model context fails because somewhere in there it still tries to validate the old value. Thanks!
2
0
322
Mar ’25
Is iCloud sync working?
Hello, I tried to validate if my app was properly syncing to the cloud. To test this, I created some data in the app, and then deleted the app, and reinstalled. I was expecting the data to still exist but it isn't. Is this a valid test or is the data expected to be deleted when app is deleted?
1
0
165
Mar ’25
Is there a guaranteed order for records in CKSyncEngine's handleFetchedRecordZoneChanges?
I have two recordTypes in CloudKit: Author and Book. The Book records have their parent property set to an Author, enabling hierarchical record sharing (i.e., if an Author record is shared, the participant can see all books associated with that author in their shared database). When syncing with CKSyncEngine, I was expecting handleFetchedRecordZoneChanges to deliver all Author records before their associated Book records. However, unless I’m missing something, the order appears to be random. This randomness forces me to handle two codepaths in my app (opposed to just one) to replicate CloudKit references in my local persistency storage: Book arrives before its Author → I store the Book but defer setting its parent reference until the corresponding Author arrives. Author arrives before its Books → I can immediately set the parent reference when each Book arrives. Is there a way to ensure that Author records always arrive before Book records when syncing with CKSyncEngine? Or is this behavior inherently unordered and I have to implement two codepaths?
1
0
610
Feb ’25
Correct way to remove arrays containing model objects in SwiftData
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 }
0
0
299
Dec ’24
Is it possible to track history using HistoryDescriptor in SwiftData?
Is it possible to track history using the new HistoryDescriptor feature in SwiftData? Or can I only get the current most recent data? Or is it possible to output the changed data itself, along with timestamps? I am hoping that it is possible to track by a standard feature like NSPersistentHistoryTransaction in CoreData. Do we still have to use a method in SwiftData that creates more tracking data itself?
4
0
1.2k
Feb ’25