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

NSPersistentCloudKitContainer in duplicate processes
I have a single multiplatform application that I use NSPersistentCloudKitContainer on. This works great, except I noticed when I open two instances of the same process (not windows) on the same computer, which share the same store, data duplication and "Metadata Inconsistency" errors start appearing. This answer (https://stackoverflow.com/a/67243833) says this is not supported with NSPersistentCloudKitContainer. Is this indeed true? If it isn't allowed, is the only solution to disable multiple instances of the process via a lock file? I was thinking one could somehow coordinate a single "leader" process that syncs to the cloud, with the others using NSPersistentContainer, but this would be complicated when the "leader" process terminates. Currently, it seems iPad split views are new windows, not processes -- but overall I'm still curious :0 Thank you!
0
0
48
6h
NSPersistentCloudKitContainer data loss edge case
Hi, I was testing the new iOS 18 behavior where NSPersistentCloudKitContainer wipes the local Core Data store if the user logs out of iCloud, for privacy purposes. I ran the tests both with a Core Data + CloudKit app, and a simple one using SwiftData with CloudKit enabled. Results were identical in either case. In my testing, most of the time, the feature worked as expected. When I disabled iCloud for my app, the data was wiped (consistent with say the Notes app, except if you disable iCloud it warns you that it'll remove those notes). When I re-enabled iCloud, the data appeared. (all done through the Settings app) However, in scenarios when NSPersistentCloudKitContainer cannot immediately sync -- say due to rate throttling -- and one disables iCloud in Settings, this wipes the local data store and ultimately results in data loss. This occurs even if the changes to the managed objects are saved (to the local store) -- it's simply they aren't synced in time. It can be a little hard to reproduce the issue, especially since when you exit to the home screen from the app, it generally triggers a sync. To avoid this, I swiped up to the screen where you can choose which apps to close, and immediately closed mine. Then, you can disable iCloud, and run the app again (with a debugger is helpful). I once saw a message with something along the lines of export failed (for my record that wasn't synced), and unfortunately it was deleted (and never synced). Perhaps before NSPersistentCloudKitContainer wipes the local store it ought to force sync with the cloud first?
2
0
106
15h
Best practice for centralizing SwiftData query logic and actions in an @Observable manager?
I'm building a SwiftUI app with SwiftData and want to centralize both query logic and related actions in a manager class. For example, let's say I have a reading app where I need to track the currently reading book across multiple views. What I want to achieve: @Observable class ReadingManager { let modelContext: ModelContext // Ideally, I'd love to do this: @Query(filter: #Predicate<Book> { $0.isCurrentlyReading }) var currentBooks: [Book] // ❌ But @Query doesn't work here var currentBook: Book? { currentBooks.first } func startReading(_ book: Book) { // Stop current book if any if let current = currentBook { current.isCurrentlyReading = false } book.isCurrentlyReading = true try? modelContext.save() } func stopReading() { currentBook?.isCurrentlyReading = false try? modelContext.save() } } // Then use it cleanly in any view: struct BookRow: View { @Environment(ReadingManager.self) var manager let book: Book var body: some View { Text(book.title) Button("Start Reading") { manager.startReading(book) } if manager.currentBook == book { Text("Currently Reading") } } } The problem is @Query only works in SwiftUI views. Without the manager, I'd need to duplicate the same query in every view just to call these common actions. Is there a recommended pattern for this? Or should I just accept query duplication across views as the intended SwiftUI/SwiftData approach?
0
0
102
3d
SwiftData .autosaveEnabled / rollback() trouble
Hello, In my iOS/SwiftUI/SwiftData app, I want the user to be able to hit [Cancel] from editing in a detail screen and return to the previous screen without changes being saved. I believed that setting autosaveEnabled to false and/or calling .rollback would prevent changes from being saved, unless/until I call .save() when the user clicks [Save], but this does not seem to be correct. I set modelContext.autosaveEnabled = false and I call modelContext.rollback() when the user hits [Cancel], but any changes they made are not rolled back, but saved even if I don’t call save(). I have tried setting autosaveEnabled to false when I create the ModelContainer on a @MainActor function when the App starts, and in the detail/edit screen’s .onAppear(). I can see that .rollback is being called when the [Cancel] button is tapped. In all cases, any changes the user made before hitting [Cancel] are saved. The Developer Documentation on autosaveEnabled includes this: “The default value is false. SwiftData automatically sets this property to true for the model container’s mainContext." I am working on the mainContext, but it appears that setting autosaveEnabled to false has no effect no matter where in the code I set it. If someone sees what I am doing wrong, I’d sure appreciate the input. If this description doesn’t explain the problem well enough, I’ll develop a minimal focused example.
4
1
134
4d
How to distinguish which operations in the file provider are during offline period
Currently tested, if the file provider goes offline (referring to calling disconnect) and deletes a file, the system will automatically trigger the deleteItems event after reconnecting (note that only after calling reconnect again will the current deleteItems logic be reached). However, for offline deletion, I would like to pass it directly without operating on the cloud. Can mounting disks determine which operations were performed offline during reboot
1
0
58
6d
Git and iCloud
Hi guys, also those at Apple, I love what you all do and make, long time Linux user switched since silicon. But is there perhaps any timeline on improving the interaction between iCloud and git? Perhaps it is on me to check beforehand, but I enabled Desktop & Doc sync on iCloud (which included some git repos) and these now malfunction completely. Bad object errors, lost wheels, insanely long syncing, and worst of all - randomly removed environment variables! I only noticed when random stuff stopped working out of the blue; only after re-configuring zsh and doing scorched earth on brew did it click. I mean, there is a '.nosync' flaggy thing to add to dirs, but it isn't even officially supported. Moreover, when trying to disable sync for docs, it will delete local repos! So either it's disabling and starting all over again, or waiting for the sync to finish (which breaks things) and going through a long restoration process. I don't expect iCloud for the average Joe to be super specced for developers, but perhaps there could be room for some minor improvements that would at least prevent git repositories from completely breaking, e.g. just ignoring them or not syncing certain folder/file types. Restoring the whole thing (if even possible) is an extremely long and tedious process. Sorry for the rant, but I feel this might be appreciated. One of the things I like about this ecosystem, proprietary it is, is the seemliness and easy of use. If iCloud Drive is advertised as 'it will work', it's only fair that this would apply to developers too (and that they are not required to check beforehand whether it will break all of their git repositories). Or it is just me getting old. :) Cheers, Frans
0
0
24
6d
Macos uses NSFilePrefertAction and userInfo to implement context menu, but it does not take effect
On the macOS platform, I am planning to use the combination of NSFileProviders Custom Action and userInfo to implement custom context menus. However, the NSExtensions FileProviders Action Activation Rule in info does not work as long as it is related to userInfo. Are there any restrictions on the use of this userInfo? keepDownloaded is bool value
0
0
53
6d
SwiftData @Model: Optional to-many relationship is never nil at runtime
Hi all, I’m trying to understand SwiftData’s runtime semantics around optional to-many relationships, especially in the context of CloudKit-backed models. I ran into behavior that surprised me, and I’d like to confirm whether this is intended design or a potential issue / undocumented behavior. Minimal example import SwiftUI import SwiftData @Model class Node { var children: [Node]? = nil var parent: Node? = nil init(children: [Node]? = nil, parent: Node? = nil) { self.children = children self.parent = parent print(self.children == nil) } } struct ContentView: View { var body: some View { Button("Create") { _ = Node(children: nil) } } } Observed behavior If @Model is not used, children == nil prints true as expected. If @Model is used, children == nil prints false. Inspecting the macro expansion, it appears SwiftData initializes relationship storage using backing data placeholders and normalizes to-many relationships into empty collections at runtime, even when declared as optional. CloudKit context From the SwiftData + CloudKit documentation: “The iCloud servers don’t guarantee atomic processing of relationship changes, so CloudKit requires all relationships to be optional.” Because of this, modeling relationships as optional is required when syncing with CloudKit, even for to-many relationships. This is why I’m hesitant to simply switch the model to a non-optional [Node] = [], even though that would match the observed runtime behavior. Questions Is it intentional that optional to-many relationships in SwiftData are never nil at runtime, and instead materialize as empty collections? If so, is Optional<[Model]> effectively treated as [Model] for runtime access, despite being required for CloudKit compatibility? Is the defaultValue: nil in the generated Schema.PropertyMetadata intended only for schema/migration purposes rather than representing a possible runtime state? Is there a recommended modeling pattern for CloudKit-backed SwiftData models where relationships must be optional, but runtime semantics behave as non-optional? I’m mainly looking to ensure I’m aligning with SwiftData’s intended design and not relying on behavior that could change or break with CloudKit sync. Thanks in advance for any clarification!
0
0
48
6d
Best approach for persisting anonymous user data across devices without account creation
I'm building a photo editing app with a token-based subscription system using RevenueCat and StoreKit. Users purchase subscriptions that grant tokens for AI generations. There are no user accounts, the app is fully anonymous. Currently, I generate an anonymous account ID via RevenueCat SDK and store it in iCloud Keychain. This allows users on the same iCloud account to restore both their subscription and token balance across devices. However, users on a different iCloud account can restore their subscription via Apple, but their token balance is lost because there's no way to link the anonymous IDs. The problem is that if a user switches iCloud accounts or gets a new device without the same iCloud, their purchased tokens are orphaned. The subscription restores fine through Apple, but the token balance tied to the old anonymous ID becomes inaccessible. I have a few constraints: no user accounts, no email or phone sign-in, must work across devices owned by the same person, and must comply with App Store guidelines. My questions are: Is iCloud Keychain the right tool for this, or is there a better approach? Would CloudKit with an anonymous record zone be more appropriate? Are there any recommended patterns for persisting consumable balances tied to anonymous users across device migrations? Any guidance would be appreciated.
0
0
27
6d
Asset Pack Limit
I have a total of 100 asset packs associated with my app but I have archived 5 of them. Unfortunately I am now unable to upload any more asset packs (the reported error is "backgroundAsset limit reached -- This app has already reached the maximum number of active backgroundAssets. Maximum allowed is 100.") I assumed that archiving asset packs would make them inactive (and thus not count against the limit). This seems to not be the case and I'm not sure how I can upload new asset packs.
3
0
82
1w
AgeRangeService system prompt does not allow displaying upper age threshold (e.g. 18+)
We are using AgeRangeService.requestAgeRange(ageGates:in:) with an age gate of 18 to verify adult users. The system prompt always displays the lower-bound wording (“17 or Younger”), even when the app’s requirement is to verify users who are 18 or older. We understand the UI is system-controlled; however, this wording causes confusion for users, QA, and product teams, as it appears to indicate a child-only flow even when requesting adult verification. Based on the demonstration video, it appears that they have another more coherent message. In Apple's example, it is different, and it is correct that we need to specify 18 years or older in the implementation. A little more context might be helpful, but we are creating a kind of wrapper with React Native that receives that value as a parameter, which is 18.
2
0
151
1w
CloudKit CKRecordZone Deletion Issue
CloudKit CKRecordZone Deletion Issue Problem: CloudKit record zones deleted via CKDatabase.modifyRecordZones(deleting:) or CKModifyRecordZonesOperation are successfully removed but then reappear. I suspect they are automatically reinstated by CloudKit sync, despite successful deletion confirmation. Environment: SwiftData with CloudKit integration Custom CloudKit zones created for legacy zone-based sharing Observed Behavior: Create custom zone (e.g., "TestZone1") via CKDatabase.modifyRecordZones(saving:) Copy records to zone for sharing purposes Delete zone using any CloudKit deletion API - returns success, no errors Immediate verification: Zone is gone from database.allRecordZones() After SwiftData/CloudKit sync or app restart: Zone reappears Reproduction: Tested with three different deletion methods - all exhibit same behaviour: modifyRecordZones(deleting:) async API CKModifyRecordZonesOperation (fire-and-forget) CKModifyRecordZonesOperation with result callbacks Zone deletion succeeds, change tokens (used to track updates to shared records) cleaned up But zones are restored presumably by CloudKit background sync Expected: Deleted zones should remain deleted Actual: Zones are reinstated, creating orphaned zones
1
0
70
1w
Swift Data Undo
Trying to support undo & redo in an app that utilizes Swift Data and as with anything other than provided simplistic Apple demo examples the experience is not great. The problem: Im trying to build functionality that allows users to add items to an item group, where item and item group have a many-to-many relationship e.g. item group can hold many items and items can appear in multiple groups. When trying to do so with relatively simple setup of either adding or removing item group from items relationship array, I am pretty consistently met with a hard crash after performing undo & redo. Sometimes it works the first few undo & redos but 95% of the time would crash on the first one. Could not cast value of type 'Swift.Optional<Any>' (0x20a676be0) to 'Swift.Array<App.CodableStructModel>' (0x207a2bc08). Where CodableStructModel is a Codable Value type inside Item. Adding and removing this relationship should be undoable & redoable as typical for Mac interaction and is "supported" by SwiftData by default, meaning that the developer has to actively either wholly opt out of undo support in their modelContainer setup or do it on a per action scale with the only thing I know of: modelContext.processPendingChanges() modelContext.undoManager?.disableUndoRegistration() ..... modelContext.processPendingChanges() modelContext.undoManager?.enableUndoRegistration() General rant on SwiftData: Random crashes, inconsistencies, random cryptic errors thrown by the debugger and general lack of production level stability. Each update breaks something new and there is very little guidance and communication from the Swift Data team on how to adapt and more importantly consideration for developers that have adopted Swift Data. If SwiftData is not ready for production, it would go a long way to clearly communicate that and mark it as Beta product.
1
0
92
1w
SwiftData with CloudKit Sync Issue
I am using SwiftData with CloudKit to synchronize data across multiple devices, and I have encountered an issue: occasionally, abnormal sync behavior occurs between two devices (it does not happen 100% of the time—only some users have reported this problem). It seems as if synchronization between the two devices completely stops; no matter what operations are performed on one end, the other end shows no response. After investigating, I suspect the issue might be caused by both devices simultaneously modifying the same field, which could lead to CloudKit's logic being unable to handle such conflicts and causing the sync to stall. Are there any methods to avoid or resolve this situation? Of course, I’m not entirely sure if this is the root cause. Has anyone encountered a similar issue?
0
0
93
3w
SwiftData crash when enabling CloudKit for existing users (Free to Pro upgrade)
Hi, I am implementing a premium feature in my app where CloudKit syncing is available only for "Pro" users. The Workflow: Free Users: I initialize the ModelContainer with cloudKitDatabase: .none so their data stays local. Pro Upgrade: When a user purchases a subscription, I restart the container with cloudKitDatabase: .automatic to enable syncing. The Problem: If a user starts as "Free" (creates local data) and later upgrades to "Pro", the app crashes immediately upon launch with the following error: Fatal error: Failed to create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil) It seems that SwiftData fails to load the existing data once the configuration changes to expect a CloudKit-backed store. My Question: Is there a supported way to "toggle" CloudKit on for an existing local dataset without causing this crash? I want the user's existing local data to start syncing once they pay, but currently, it just crashes. My code: import Foundation import SwiftData public enum DataModelEnum: String { case task, calendar public static let container: ModelContainer = { let isSyncEnabled = UserDefaults.isProUser let config = ModelConfiguration( groupContainer: .identifier("group.com.yourcompany.myApp"), cloudKitDatabase: isSyncEnabled ? .automatic : .none ) do { return try ModelContainer(for: TaskModel.self, CalendarModel.self, configurations: config) } catch { fatalError("Failed to create ModelContainer: \(error)") } }() }
1
0
104
3w
iCloud Container Cannot Enable in Xcode — App ID Won’t Accept Container / Missing iCloud Documents Toggle
Hi everyone, I am experiencing an iCloud provisioning problem I cannot resolve, and Developer Support has not been able to help. My App ID: com.exaqservices.ArkyvTiles Symptoms: 1. In Xcode (v16.2), enabling iCloud in Signing & Capabilities repeatedly fails with: The app ID does not include the iCloud container. Click Try Again. Clicking Try Again does nothing. The error persists forever. 2. In Certificates, Identifiers & Profiles: • The iCloud capability is enabled for this App ID. • The CloudKit container is selected. • But the portal no longer shows the “iCloud Documents” checkbox, which used to be required for ubiquitous document support. 3. Xcode cannot regenerate provisioning profiles because it claims the App ID is missing the iCloud container — even though the container is attached. 4. Provisioning profiles on the Apple Developer site all appear expired, and new ones do not generate correctly. 5. The App Store Connect interface also does not show an iCloud Services section under App Information → Capabilities as older guides describe. Expected Behavior: Since iCloud and the CloudKit container are enabled on the App ID, Xcode should successfully enable: • com.apple.developer.icloud-services • com.apple.developer.icloud-container-identifiers • com.apple.developer.ubiquity-container-identifiers (if needed) • com.apple.developer.ubiquity-kvstore-identifier Instead, the entitlements never propagate. What I suspect: This seems like an App ID metadata mismatch or a stale backend entry where: • the CloudKit container is attached but the entitlement isn’t linked, • the “iCloud Documents” flag is missing due to a UI transition, • provisioning profiles cannot be regenerated because the App ID is not updating correctly. What I need help with: Can someone from Apple engineering confirm: • Whether my App ID metadata is corrupted, • If entitlements need to be manually refreshed, • Or if the “iCloud Documents” toggle has moved or is no longer exposed? This is blocking development completely — I cannot build, sign, or deploy the app with iCloud. Thank you! Alan Metzger
1
0
81
3w