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

MacOS CloudKit production environment is not working properly
My macOS app is developed using SwfitUI, SwiftData, and CloudKit. In the development environment, CloudKit works well. Locally added models can be quickly viewed in the CloudKit Console. macOS app and iOS app with the same BundleID can also synchronize data normally when developing locally. However, in the production environment, the macOS app cannot synchronize data with iCloud. But iOS app can. The models added in the production environment are only saved locally and cannot be viewed in CloudKit Console Production. I am sure I have configured correctly, container schema changes to deploy to the Production environment. I think there may be a problem with CloudKit in macOS. Please help troubleshoot the problem. I can provide you with any information you need. var body: some Scene { WindowGroup { MainView() .frame(minWidth: 640, minHeight: 480) .environment(mainViewModel) } .modelContainer(for: [NoteRecord.self]) } I didn't do anything special. I didn’t do anything special. I just used SwiftData hosted by CloudKit.
2
0
524
Nov ’24
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
597
Nov ’24
ModelContext.model(for:) returns deleted objects
I'm writing some tests to confirm the behavior of my app. White creating a model actor to delete objects I realized that ModelContext.model(for:) does return objects that are deleted. I was able to reproduces this with this minimal test case: @Model class Activity { init() {} } struct MyLibraryTests { let modelContainer = try! ModelContainer( for: Activity.self, configurations: ModelConfiguration( isStoredInMemoryOnly: true ) ) init() throws { let context = ModelContext(modelContainer) context.insert(Activity()) try context.save() } @Test func modelForIdAfterDelete() async throws { let context = ModelContext(modelContainer) let id = try context.fetch(FetchDescriptor<Activity>()).first!.id context.delete(context.model(for: id) as! Activity) try context.save() let result = context.model(for: id) as? Activity #expect(result == nil) // Expectation failed: (result → MyLibrary.Activity) == nil } @Test func fetchDescriptorAfterDelete() async throws { let context = ModelContext(modelContainer) let id = try context.fetch(FetchDescriptor<Activity>()).first!.id context.delete(context.model(for: id) as! Activity) try context.save() let result = try context.fetch( FetchDescriptor<Activity>(predicate: #Predicate { $0.id == id }) ).first #expect(result == nil) } } Here I create a new context, insert an model and save it. The test modelForIdAfterDelete does fail, as result still contains the deleted object. I also tried to check #expect(result!.isDeleted), but it is also false. With the second test I use a FetchDescriptor to retrieve the object by ID and it correctly returns nil. Shouldn't both methods use a consistent behavior?
2
0
95
May ’25
SwiftData propertiesToFetch question
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?
2
0
342
Feb ’25
SwiftData: var dates: [Date]? or var dates: [Date] = []
I am trying to get my head around SwiftData, and specifically some more "advanced" ideas that I have not seen covered in the various tutorials. Specifically, I have a class that includes a collection that may or may not contain elements. For now I am experimenting with a simple array of Date, and I don't know if I should make it an optional, or an empty array. Without SwiftData in the mix it seems like it's probably programmers choice, but I wonder if SwiftData handles those two scenarios differently, that would suggest one over the other.
2
0
606
Oct ’24
No persistent stores error in SwiftData
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) } } } }
2
0
130
May ’25
Core Data complaining about store being opened without persistent history tracking... but I don't think that it has been
Since running on iOS 14b1, I'm getting this in my log (I have Core Data logging enabled): error: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store at 'file:///private/var/mobile/Containers/Shared/AppGroup/415B75A6-92C3-45FE-BE13-7D48D35909AF/StoreFile.sqlite' As far as I can tell, it's impossible to open my store without that key set - it's in the init() of my NSPersistentContainer subclass, before anyone calls it to load stores. Any ideas?
2
0
1.1k
May ’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
ValueTransformer currently crashes XCode SwiftUI preview
I have a working ValueTransformer that runs fine in simulator/device, but crashes in SwiftUI Preview. Even though they are the same code. Here is my code import Foundation final class StringBoolDictTransformer: ValueTransformer { override func transformedValue(_ value: Any?) -> Any? { guard let stringBoolDict = value as? [String: Bool] else { return nil } let nsDict = NSMutableDictionary() for (key, bool) in stringBoolDict { nsDict[key] = NSNumber(value: bool) } do { let data = try NSKeyedArchiver.archivedData(withRootObject: nsDict, requiringSecureCoding: true) return data } catch { debugPrint("Unable to convert [Date: Bool] to a persistable form: \(error.localizedDescription)") return nil } } override func reverseTransformedValue(_ value: Any?) -> Any? { guard let data = value as? Data else { return nil } do { guard let nsDict = try NSKeyedUnarchiver.unarchivedDictionary(ofKeyClass: NSString.self, objectClass: NSNumber.self, from: data) else { return nil } var result = [String: Bool]() for (key, value) in nsDict { result[key as String] = value.boolValue } return result } catch { debugPrint("Unable to convert persisted Data to [Date: Bool]: \(error.localizedDescription)") return nil } } override class func allowsReverseTransformation() -> Bool { true } override class func transformedValueClass() -> AnyClass { NSDictionary.self } } and here is the container public struct SwiftDataManager { public static let shared = SwiftDataManager() public var sharedModelContainer: ModelContainer init() { ValueTransformer.setValueTransformer( StringBoolDictTransformer(), forName: NSValueTransformerName("StringBoolDictTransformer") ) let schema = Schema([, Plan.self ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { sharedModelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } } } and the model @Model final class Plan { @Attribute(.transformable(by: StringBoolDictTransformer.self)) var dict: [String: Bool] = [:] } I would get that container and pass it in appdelegate and it works fine. I would get that container and pass it inside a #Preview and it would crash with the following: Runtime: iOS 17.5 (21F79) - DeviceType: iPhone 15 Pro CoreFoundation: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "dict"; desired type = NSDictionary; given type = _NSInlineData; value = {length = 2, bytes = 0x7b7d}.' libsystem_c.dylib: abort() called Version 16.0 (16A242d)
2
0
903
Oct ’24
CKSyncEngine save existing CKRecord
I have transitioned to CKSyncEngine for syncing data to iCloud, and it is working quite well. I have a question regarding best practices for modifying and saving a CKRecord which already exists in the private or shared database. In my current app, most CKRecords will never be modified after saving to the database, so I do not persist a received record locally after updating my local data model. In the rare event that the local data for that record is modified, I manually fetch the associated server record from the database, modify it, and then use CKSyncEngine to save the modified record. As an alternative method, I can create a new CKRecord locally with the corresponding recordID and the modified data, and then use CKSyncEngine to attempt to save that record to the database. Doing so generates an error in the delegate method handleSentRecordZoneChanges, where I receive the local record I tried to save back inevent.failedRecordSaves with a .serverRecordChanged error, along with the corresponding server CKRecord. I can then update that server record with the local data and re-save using CKSyncEngine. I have not yet seen any issues when doing it this way. The advantage of the latter method is that CKSyncEngine handles the entire database operation, eliminating the manual fetch step. My question is: is this an acceptable practice, or could this result in other unforeseen issues?
2
0
72
Apr ’25
NSFetchedResultsController index out of bounds during context merging changes
I've noticed several crashes that look like they're caused by an index out of bound in internal methods of NSFetchedResultsController. This happens while changes are merged from the persistent store container into the view context. Here's an example of the last exception backtrace. Exactly which internal methods that are called in - [NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] vary between crash reports but they all end up crashing from _NSArrayRaiseBoundException. The Core Data stack consists of one persistent store, one persistent store coordinator that the view context is set up to automatically merge changes from, and data is saved to disk from background context. persistentContainer.loadPersistentStores(...) viewContext = persistentContainer.viewContext viewContext.automaticallyMergesChangesFromParent = true backgroundContext = persistentContainer.newBackgroundContext() backgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy backgroundClientContext = persistentContainer.newBackgroundContext() backgroundClientContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy Does anyone have any ideas what could be causing this? Thankful for any ideas or advice on how to investigate further.
2
0
707
Jan ’25
NSPersistentCloudKitContainer not saving 50% of the time
I'm using NSPersistentCloudKitContainer to save, edit, and delete items, but it only works half of the time. When I delete an item and terminate the app and repoen, sometimes the item is still there and sometimes it isn't. The operations are simple enough: moc.delete(thing) try? moc.save() Here is my DataController. I'm happy to provide more info as needed class DataController: ObservableObject { let container: NSPersistentCloudKitContainer @Published var moc: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "AppName") container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } #if DEBUG do { try container.initializeCloudKitSchema(options: []) } catch { print("Error initializing CloudKit schema: \(error.localizedDescription)") } #endif moc = container.viewContext } }
2
0
364
Jan ’25
How to import large data from Server and save it to Swift Data
Here’s the situation: • You’re downloading a huge list of data from iCloud. • You’re saving it one by one (sequentially) into SwiftData. • You don’t want the SwiftUI view to refresh until all the data is imported. • After all the import is finished, SwiftUI should show the new data. The Problem If you insert into the same ModelContext that SwiftUI’s @Environment(.modelContext) is watching, each insert may cause SwiftUI to start reloading immediately. That will make the UI feel slow, and glitchy, because SwiftUI will keep trying to re-render while you’re still importing. How to achieve this in Swift Data ?
2
0
92
Apr ’25
Swift 6 and NSPersistentCloudKitContainer
Hello all! I'm porting a ios15+ swiftui app to be compatible with Swift 6 and enabling strict concurrency checking gave me a warning that will be an error when switching to swift 6. I'm initializing a persistence controller for my cloud kit container: import CoreData struct PersistenceController { static let shared = PersistenceController() let container: NSPersistentCloudKitContainer init() { container = NSPersistentCloudKitContainer(name: "IBreviary") container.loadPersistentStores(completionHandler: { _, error in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy container.viewContext.automaticallyMergesChangesFromParent = true } } The warning is on the merge policy: Reference to var 'NSMergeByPropertyObjectTrumpMergePolicy' is not concurrency-safe because it involves shared mutable state; this is an error in the Swift 6 language mode I have no idea how to make this concurrency safe, nor I found a documentation entry to help me with this. Anyone have idea how to solve this? Thanks in advance V.
2
0
958
Sep ’24
Data Protection and SwiftData Containers
SwiftData ModelContainer instances don't seem to have a value for setting the Data Protection class. Is the best way to set that by setting the Data Protection in the app capabilities? Is that the only way? I have a need for log data that would be "Complete unless open" and user data that would be "Complete", but how do I change one of the containers data protection class?
2
1
835
Jan ’25
SwiftData and iCloud
I'm a first time developer for Swift, (getting on a bit!) but after programming in VB back in the late 90s I wanted to write an app for iPhone. I think I might have gone about it the wrong way, but I've got an app that works great on my iPhone or works great on my iPad. It saves the data persistently on device, but, no matter how much I try, what I read and even resorting to AI (ChatGPT & Gemini) I still can't get it to save the data on iCloud to synchronise between the two and work across the devices. I think it must be something pretty fundamental I'm doing (or more likely not doing) that is causing the issue. I'm setting up my signing and capabilities as per the available instructions but I always get a fatal error. I think it might be something to do with making fields optional, but at this point I'm second guessing myself and feeling a complete failure. Any advice or pointers would be really gratefully appreciated. I like my app and would like eventually to get it on the App Store but at this point in time I feel it should be on the failed projects heap! I've even tried a new Xcode project for iOS and asking it to use SwiftData and CloudKit - the default project should work - right? But it absolutely doesn't for me. Please send help!!
2
0
116
Apr ’25
Automatic lightweight migrations in SwiftData VersionedSchema?
Currently, I have an Unversioned Schema, and lightweight changes are automatically applied to the Models. However, I'm planning to transition to a VersionedSchema, and I have a few questions: Do I need to write all lightweight migrations in the Migration Plan? or is it automatically applied like the Unversioned Schema? What happens if I do not create a lightweight migration? and just directly do lightweight changes to the latest VersionedSchema (example: Add a new property)?
2
1
552
Dec ’24
SectionedFetchRequest in SwiftData
With Core Data and SwiftUI we can use @SectionedFetchRequest. Does SwiftData support something similar to @SectionedFetchRequest? For example, I want to create a lazy-loaded list that groups posts by their date. @Model Post { let title: String let dateString: String // YYYY-MM-DD let createdAt: Date } @SectionedFetchRequest( entity: \Post.self, sectionIdentifier: \Post.dateString, sortDescriptors: [\Post.createdAt] ) var postsByDate: SectionedFetchResults ForEach(postsByDate) { section in Section(header: Text(section.id)) { ForEach(section) { post in PostView(post) } } }
2
1
486
Sep ’24
Migrate Core Data to SwiftData in an App Group (& CloudKit)
Hello, I’m upgrading my app from Core Data to SwiftData. Due to my old setup the Core Data store has an explicitly name like „Something.sqlite“, because it was defined via NSPersistentContainer(name: "Something") before switching to SwiftData. Now my goal is to migrate the Core Data stack to SwiftData, while moving it to an App Group (for Widget support) as well as enable iCloud sync via CloudKit. Working Migration without App Group & CloudKit I’ve managed to get my migration running without migrating it to an App Group and CloudKit support like so: @main struct MyAppName: App { let container: ModelContainer init() { // Legacy placement of the Core Data file. let dataUrl = URL.applicationSupportDirectory.appending(path: "Something.sqlite") do { // Create SwiftData container with migration and custom URL pointing to legacy Core Data file container = try ModelContainer( for: Foo.self, Bar.self, migrationPlan: MigrationPlan.self, configurations: ModelConfiguration(url: dataUrl)) } catch { fatalError("Failed to initialize model container.") } } var body: some Scene { WindowGroup { ContentView() } .modelContainer(container) } } How To Migrate to App Group & CloudKit? I’ve already tried to use the ModelConfiguration with a name, but it seems to only look for a .store file and thus doesn’t copy over the Core Data contents. let fullSchema = Schema([Foo.self, Bar.self]) let configuration = ModelConfiguration("Something", schema: fullSchema) Can someone help me how to do this migration or point me into the right direction? I can’t find anything relating this kind of migration …
2
1
1.9k
Dec ’24
Core Data not returning results in ShieldConfiguration Extension, but works fine in other extensions
Hi everyone, I’m using Core Data in several extensions (DeviceActivityMonitor, ShieldAction, and ShieldConfiguration). It works perfectly in DeviceActivityMonitor and ShieldAction. I’m able to successfully fetch data and log the correct count using a fetch request. However, when I try the same setup in the ShieldConfiguration extension, the fetch request always returns 0 results. The CoreData and App Group setup appears to be correct since the first two extensions fetch the expected data. I’ve also previously tested storing the CoreData objects separately in a JSON-FIle using FileManager and it worked without issues—though I’d prefer not to handle manual encoding/decoding if possible. The documentation mentions that the extension runs in a sandbox, restricting network requests or moving sensitive content. But shouldn’t reading data (from a shared App Group, for instance) still be possible within the sandbox, as it is the case with the Files, what is the difference there? In my case, I only need to read the data, as modifications can be handled via ShieldActionExtension. Any help would be greatly appreciated!
2
0
979
Oct ’24