iCloud & Data

RSS for tag

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

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

iCloud problem
I use microsoft office excel 2007. When I save a file located in the icloud, the file (often) turns into this the problem, for example, is that excel does not see this file (I'm trying to open it from excel) when I try to open the file manually, it says: The actual format of the file you are trying to open (26068000) is different from the file extension indicated. Before opening this file, make sure it is not corrupted and comes from a trusted source. Do you want to open this file now? icloud' developers, please fix it, thx.
0
0
21
2h
Why purgeObjectsAndRecordsInZone(with:in:completion:) doesn’t work?
I want to clear all the data in the zone, but I can't delete it. Below is my code, no logs are printed when running. static func clearData() { let coordinator = shared.container.persistentStoreCoordinator let fm = FileManager.default for d in shared.container.persistentStoreDescriptions { guard let url = d.url else { continue } do { if fm.fileExists(atPath: url.path()) { try coordinator.destroyPersistentStore(at: url, type: .sqlite) } } catch { logger.debug("Failed to delete db file, \(error)") } } for description in shared.container.persistentStoreDescriptions { guard let originalStoreURL = description.url else { continue } let walFileURL = originalStoreURL.deletingPathExtension().appendingPathExtension("sqlite-wal") let shmFileURL = originalStoreURL.deletingPathExtension().appendingPathExtension("sqlite-shm") for url in [originalStoreURL, walFileURL, shmFileURL] { do { if fm.fileExists(atPath: url.path()) { try fm.removeItem(at: url) } } catch { logger.debug("Failed to delete db file, \(error)") } } } let container = CKContainer(identifier: appContainerID) container.privateCloudDatabase.fetchAllRecordZones { zones, error in if let error = error { print("Error fetching zones: ") } else if let zone = zones?.first, zone.zoneID.zoneName == "_defaultZone" { PersistenceController.shared.container.purgeObjectsAndRecordsInZone(with: zone.zoneID, in: nil) { ckShare, error in if let error = error { print("Error purge zones: \(error)") } if ckShare == nil { print("ckShare is nil") } } } } }
0
0
40
7h
SwiftData Migration: Keeps failing at the end of willMigrate
I've been trying to setup a successful migration, but it keeps failing with this error: NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore. I can't find any information about this online. I added breakpoints throughout the code in willMigrate, and it originally failed on this line: try? context.save() I removed that, and it still failed. After I reload the app, it doesn't run the migration again and the app loads successfully. I figured since it crashed, it would keep trying, but I guess not. Here's how my migration is setup. enum MigrationV1ToV2: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] } static var stages: [MigrationStage] { [stage] } static let stage = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self, willMigrate: { context in // Get cycles let cycles = try? context.fetch(FetchDescriptor<SchemaV1.Cycle>()) if let cycles { for cycle in cycles { // Create new recurring objects based on what's in the cycle for income in cycle.income { let recurring = SchemaV2.Recurring(name: income.name, frequency: income.frequency, kind: .income) recurring.addAmount(.init(date: cycle.startDate, amount: income.amount)) context.insert(recurring) } for expense in cycle.expenses { let recurring = SchemaV2.Recurring(name: expense.name, frequency: expense.frequency, kind: .expense) recurring.addAmount(.init(date: cycle.startDate, amount: expense.amount)) context.insert(recurring) } for savings in cycle.savings { let recurring = SchemaV2.Recurring(name: savings.name, frequency: savings.frequency, kind: .savings) recurring.addAmount(.init(date: cycle.startDate, amount: savings.amount)) context.insert(recurring) } for investment in cycle.investments { let recurring = SchemaV2.Recurring(name: investment.name, frequency: investment.frequency, kind: .investment) recurring.addAmount(.init(date: cycle.startDate, amount: investment.amount)) context.insert(recurring) } } //try? context.save() } else { print("The cycles were not able to be fetched.") } }, didMigrate: { context in // Get new recurring objects let newRecurring = try? context.fetch(FetchDescriptor<SchemaV2.Recurring>()) if let newRecurring { for recurring in newRecurring { // Get all recurring with the same name and kind let sameName = newRecurring.filter({ $0.name == recurring.name && $0.kind == recurring.kind }) // Add amount history to recurring object, and then remove matching for match in sameName { recurring.amountHistory.append(contentsOf: match.amountHistory) context.delete(match) } } //try? context.save() } else { print("The new recurring objects could not be fetched.") } } ) } Here's is my modelContainer in the app file. There is a fatal error occurring here that's crashing the app. var sharedModelContainer: ModelContainer = { let schema = Schema(versionedSchema: SchemaV2.self) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer( for: schema, migrationPlan: MigrationV1ToV2.self, configurations: [modelConfiguration] ) } catch { fatalError("Could not create ModelContainer: \(error)") } }() Does anyone have any suggestions for this? EDIT: I found this error in the console that may be relevant. BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered (com.apple.coredata.cloudkit.activity.export.8F7A1261-4324-40B4-B041-886DF36FBF0A). CloudKit setup failed because it couldn't register a handler for the export activity. There is another instance of this persistent store actively syncing with CloudKit in this process. And here is the fatal error Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
0
0
56
2d
SwiftData: Model Container fails completely when CloudKit storage is full
struct ModelContainerSetup { static let shared = ModelContainerSetup() private static let containerIdentifier = "iCloud.Journal" func setupModelContainer() -> ModelContainer { let schema = Schema([User.self]) let modelConfiguration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: false, cloudKitDatabase: .private(Self.containerIdentifier) ) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } } **Expected Behavior: ** When CloudKit storage is full, the app should continue functioning with local storage Data should persist locally even if cloud sync fails Sync should resume when storage becomes available **Actual Behavior: ** ModelContainer initialization fails completely Local data also stops getting saved **Environment: ** iOS 17.0+ SwiftData Private CloudKit database Ideal Behaviour: When iCloud fails, the data should still be saved locally. I do not want to have two different containers so that I can maintain data consistency.
0
0
62
3d
SwiftData: How can I tell if a migration went through successfully?
I created 2 different schemas, and made a small change to one of them. I added a property to the model called "version". To see if the migration went through, I setup the migration plan to set version to "1.1.0" in willMigrate. In the didMigrate, I looped through the new version of Tags to check if version was set, and if not, set it. I did this incase the willMigrate didn't do what it was supposed to. The app built and ran successfully, but version was not set in the Tag I created in the app. Here's the migration: enum MigrationPlanV2: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [DataSchemaV1.self, DataSchemaV2.self] } static let stage1 = MigrationStage.custom( fromVersion: DataSchemaV1.self, toVersion: DataSchemaV2.self, willMigrate: { context in let oldTags = try? context.fetch(FetchDescriptor<DataSchemaV1.Tag>()) for old in oldTags ?? [] { let new = Tag(name: old.name, version: "Version 1.1.0") context.delete(old) context.insert(new) } try? context.save() }, didMigrate: { context in let newTags = try? context.fetch(FetchDescriptor<DataSchemaV2.Tag>()) for tag in newTags ?? []{ if tag.version == nil { tag.version = "1.1.0" } } } ) static var stages: [MigrationStage] { [stage1] } } Here's the model container: var sharedModelContainer: ModelContainer = { let schema = Schema(versionedSchema: DataSchemaV2.self) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer( for: schema, migrationPlan: MigrationPlanV2.self, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() I ran a similar test prior to this, and got the same result. It's like the code in my willMigrate isn't running. I also had print statements in there that I never saw printed to the console. I tried to check the CloudKit console for any information, but I'm having issues with that as well (separate post). Anyways, how can I confirm that my migration was successful here?
0
0
93
4d
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
65
4d
SwiftData: Migrate from un-versioned to versioned schema
I've realized that I need to use migration plans, but those required versioned schemas. I think I've updated mine, but I wanted to confirm if this was the proper procedure. To start, none of my models were versioned. I've since wrapped them in a VersionedSchema like this: enum TagV1: VersionedSchema { static var versionIdentifier: Schema.Version = .init(1, 0, 0) static var models: [any PersistentModel.Type] { [Tag.self] } @Model final class Tag { var id = UUID() var name: String = "" // Relationships var transactions: [Transaction]? = nil init(name: String) { self.name = name } } } I also created a type alias to point to this. typealias Tag = TagV1.Tag This is what my container looks like in my app file. var sharedModelContainer: ModelContainer = { let schema = Schema([ Tag.self ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() The application builds and run successfully. Does this mean that my models are successfully versioned now? I'm trying to avoid an error I came across in earlier testing. That occurred because none of my models were versioned and I tried to setup a migration plan Cannot use staged migration with an unknown coordinator model version.
0
0
92
4d
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
104
5d
Sync SwiftData via CloudKit on App Start
I have an app that uses SwiftData with CloudKit to synchronize data across a users devices. I'm able to replicate data created on one device on another and when removing data, it is also removed on the other device. So, I know that SwiftData and CloudKit are configured correctly. What I'd like to do though, is to ensure that if a user installs the app on an additional device, that the data is synchronized upon app start. When testing my app on a third device, via TestFlight, there was no data in the app upon launch even though all three devices are using the same Apple account (e.g. Apple ID). What is the best way to achieve this?
4
1
117
6d
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
128
1w
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
135
1w
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
101
1w
Getting a crash for SwiftData that only happens on iPhone 16 pro
I'm getting a crash in SwiftData but only on one specific device (iPhone 16 pro running 18.2 22C5131e) and not on an ipad or simulator I cant troubleshoot this crash and its quite frustrating, all I am getting is @Query(sort: \Todo.timestamp, order: .reverse) private var todos: [Todo] ForEach(todos.filter { !$0.completed }) { item in // <---crash TodoListView() } and the error is Thread 1: signal SIGABRT An abort signal terminated the process. Such crashes often happen because of an uncaught exception or unrecoverable error or calling the abort() function. and _SwiftData_SwiftUI.Query.wrappedValue.getter : τ_0_1 -> 0x105b98b58 <+160>: ldur x8, [x29, #-0x40] 0x105b98b5c <+164>: ldur x0, [x29, #-0x38] 0x105b98b60 <+168>: ldur x1, [x29, #-0x30] 0x105b98b64 <+172>: ldur x9, [x29, #-0x20] 0x105b98b68 <+176>: stur x9, [x29, #-0x28] 0x105b98b6c <+180>: ldr x8, [x8, #0x8] 0x105b98b70 <+184>: blr x8 0x105b98b74 <+188>: ldur x0, [x29, #-0x28] 0x105b98b78 <+192>: sub sp, x29, #0x10 0x105b98b7c <+196>: ldp x29, x30, [sp, #0x10] 0x105b98b80 <+200>: ldp x20, x19, [sp], #0x20 0x105b98b84 <+204>: ret How do I fix this?
0
0
151
1w
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.
0
0
78
1w
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 } }
1
0
109
1w
Questions about CloudKit cross-device synchronization
The same macOS app is logged into the same iCloud account on two Macs. The apps on both devices can sync data with iCloud, but the data between them is isolated. When I was developing, I just enabled the CloudKit(SwiftData host in iCloud) capability and did not do anything special. I thought that the same app and the same iCloud account should sync the same data between different devices. Why is the cloud data on these two Macs isolated?
1
0
123
1w
CKSyncEngine and desiredKeys
I have a CKRecord that references an CKAsset. If I understand it correctly, CKSyncEngine would download the asset every time the record has changed on the server. (Of course it would try to use the local asset cache, but worst-case it might be already flushed) The documentation for CKAsset says that asset downloads can be prevented by limiting the requested record keys using the desiredKeys property on the fetch operation. But I don't see any possibility to set this property when using CKSyncEngine. Did I miss something? Are there any alternatives?
2
0
70
1w
Can't get iCloud root directory on iCould Documents
I couldn't get iCloud root directory ("iCloud Drive not available or user domain not found."). Anybody had similar issue? I don't want to CloudKit. Xcode: Version 16.0 I have done below: Settings > iCloud Backup ON Settings > iCloud > iCloud Drive ON Settings > iCloud > MyApp ON import Foundation import UIKit class BackupManager { var isiCloudEnabled: Bool { (FileManager.default.ubiquityIdentityToken != nil) } // Get the iCloud Drive folder and create a folder if needed func createFolder() -> URL? { let fileManager = FileManager.default // Access the iCloud Drive root directory (user-visible folder) guard let iCloudRootURL = fileManager.url(forUbiquityContainerIdentifier: nil)? .appendingPathComponent("Documents") else { print("iCloud Drive not available or user domain not found.") return nil } // Check if the folder exists in iCloud Drive root, if not, create it if !fileManager.fileExists(atPath: iCloudRootURL.path) { do { try fileManager.createDirectory(at: iCloudRootURL, withIntermediateDirectories: true, attributes: nil) print("Folder created in iCloud Drive") } catch { print("Error creating folder: \(error.localizedDescription)") return nil } } // Return the URL of the folder in iCloud Drive return iCloudRootURL } }
1
0
64
1w