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

iCloud Drive changes in iOS 18.4 and later break stated API
The NSMetadataUbiquitousItemDownloadingStatusKey indicates the status of a ubiquitous (iCloud Drive) file. A key value of NSMetadataUbiquitousItemDownloadingStatusDownloaded is defined as indicating there is a local version of this file available. The most current version will get downloaded as soon as possible . However this no longer occurs since iOS 18.4. A ubiquitous file may remain in the NSMetadataUbiquitousItemDownloadingStatusDownloaded state for an indefinite period. There is a workaround: call [NSFileManager startDownloadingUbiquitousItemAtURL: error:] however this shouldn't be necessary, and introduces delays over the previous behaviour. Has anyone else seen this behaviour? Is this a permanent change? FB17662379
0
0
62
May ’25
#Predicate doesn't work with enum
Problem The following code doesn't work: let predicate = #Predicate<Car> { car in car.size == size //This doesn't work } Console Error Query encountered an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate) Root cause Size is an enum, #Predicate works with other type such as String however doesn't work with enum Enum value is saved however is not filtered by #Predicate Environment Xcode: 15.0 (15A240d) - App Store macOS: 14.0 (23A339) - Release Candidate Steps to reproduce Run the app on iOS 17 or macOS Sonoma Press the Add button Notice that the list remains empty Expected behaviour List should show the newly created small car Actual behaviour List remains empty inspite of successfully creating the small car. Feedback FB13194334 Code Size enum Size: String, Codable { case small case medium case large } Car import SwiftData @Model class Car { let id: UUID let name: String let size: Size init( id: UUID, name: String, size: Size ) { self.id = id self.name = name self.size = size } } ContentView struct ContentView: View { var body: some View { NavigationStack { CarList(size: .small) } } CarList import SwiftUI import SwiftData struct CarList: View { let size: Size @Environment(\.modelContext) private var modelContext @Query private var cars: [Car] init(size: Size) { self.size = size let predicate = #Predicate<Car> { car in car.size == size //This doesn't work } _cars = Query(filter: predicate, sort: \.name) } var body: some View { List(cars) { car in VStack(alignment: .leading) { Text(car.name) Text("\(car.size.rawValue)") Text(car.id.uuidString) .font(.footnote) } } .toolbar { Button("Add") { createCar() } } } private func createCar() { let name = "aaa" let car = Car( id: UUID(), name: name, size: size ) modelContext.insert(car) } }
6
1
2.3k
May ’25
CoreData Data Sharing with AppGroup
I have the following lines of code to access data through CoreData. import Foundation import CoreData import CloudKit class CoreDataManager { static let instance = CoreDataManager() let container: NSPersistentCloudKitContainer let context: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "ABC") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { print(error.userInfo) } }) context = container.viewContext context.automaticallyMergesChangesFromParent = true context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) } func save() { do { try container.viewContext.save() print("Saved successfully") } catch { print("Error in saving data: \(error.localizedDescription)") } } } I have confirmed that I can share data between iPhone and iPad. Now, I need to use AppGroup as well. I have changed my code as follows. import Foundation import CoreData import CloudKit class CoreDataManager { static let shared = CoreDataManager() let container: NSPersistentContainer let context: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "ABC") container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "some group name")!.appendingPathComponent("CoreDataMama.sqlite"))] container.loadPersistentStores(completionHandler: { (description, error) in if let error = error as NSError? { print("Unresolved error \(error), \(error.userInfo)") } }) context = container.viewContext context.automaticallyMergesChangesFromParent = true context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) } func save() { do { try container.viewContext.save() print("Saved successfully") } catch { print("Error in saving data: \(error.localizedDescription)") } } } Other files being unaltered, my sample apps aren't sharing data. What am I doing wrong? Just FYI, I'm using actual devices. Thank you for your reading this topic.
1
0
65
May ’25
ForEach and RandomAccessCollection
I'm trying to build a custom FetchRequest that I can use outside a View. I've built the following ObservableFetchRequest class based on this article: https://augmentedcode.io/2023/04/03/nsfetchedresultscontroller-wrapper-for-swiftui-view-models @Observable @MainActor class ObservableFetchRequest&lt;Result: Storable&gt;: NSObject, @preconcurrency NSFetchedResultsControllerDelegate { private let controller: NSFetchedResultsController&lt;Result.E&gt; private var results: [Result] = [] init(context: NSManagedObjectContext = .default, predicate: NSPredicate? = Result.E.defaultPredicate(), sortDescriptors: [NSSortDescriptor] = Result.E.sortDescripors) { guard let request = Result.E.fetchRequest() as? NSFetchRequest&lt;Result.E&gt; else { fatalError("Failed to create fetch request for \(Result.self)") } request.predicate = predicate request.sortDescriptors = sortDescriptors controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) super.init() controller.delegate = self fetch() } private func fetch() { do { try controller.performFetch() refresh() } catch { fatalError("Failed to fetch results for \(Result.self)") } } private func refresh() { results = controller.fetchedObjects?.map { Result($0) } ?? [] } var predicate: NSPredicate? { get { controller.fetchRequest.predicate } set { controller.fetchRequest.predicate = newValue fetch() } } var sortDescriptors: [NSSortDescriptor] { get { controller.fetchRequest.sortDescriptors ?? [] } set { controller.fetchRequest.sortDescriptors = newValue.isEmpty ? nil : newValue fetch() } } internal func controllerDidChangeContent(_ controller: NSFetchedResultsController&lt;any NSFetchRequestResult&gt;) { refresh() } } Till this point, everything works fine. Then, I conformed my class to RandomAccessCollection, so I could use in a ForEach loop without having to access the results property. extension ObservableFetchRequest: @preconcurrency RandomAccessCollection, @preconcurrency MutableCollection { subscript(position: Index) -&gt; Result { get { results[position] } set { results[position] = newValue } } public var endIndex: Index { results.endIndex } public var indices: Indices { results.indices } public var startIndex: Index { results.startIndex } public func distance(from start: Index, to end: Index) -&gt; Int { results.distance(from: start, to: end) } public func index(_ i: Index, offsetBy distance: Int) -&gt; Index { results.index(i, offsetBy: distance) } public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -&gt; Index? { results.index(i, offsetBy: distance, limitedBy: limit) } public func index(after i: Index) -&gt; Index { results.index(after: i) } public func index(before i: Index) -&gt; Index { results.index(before: i) } public typealias Element = Result public typealias Index = Int } The issue is, when I update the ObservableFetchRequest predicate while searching, it causes a Index out of range error in the Collection subscript because the ForEach loop (or a List loop) access a old version of the array when the item property is optional. List(request, selection: $selection) { item in VStack(alignment: .leading) { Text(item.content) if let information = item.information { // here's the issue, if I leave this out, everything works Text(information) .font(.callout) .foregroundStyle(.secondary) } } .tag(item.id) .contextMenu { if Item.self is Client.Type { Button("Editar") { openWindow(ClientView(client: item as! Client), id: item.id!) } } } } Is it some RandomAccessCollection issue or a SwiftUI bug?
0
0
62
May ’25
Export/Import data with SwiftData
Hi ! Would anyone know (if possible) how to create backup files to export and then import from the data recorded by SwiftData? For those who wish, here is a more detailed explanation of my case: I am developing a small management software with customers and events represented by distinct classes. I would like to have an "Export" button to create a file with all the instances of these 2 classes and another "Import" button to replace all the old data with the new ones from a previously exported file. I looked for several solutions but I'm a little lost...
0
0
82
May ’25
NSMetadataQuery not searching subdirectories in external ubiquity container
Testing Environment: iOS 18.4.1 / macOS 15.4.1 I am working on an iOS project that aims to utilize the user's iCloud Drive documents directory to save a specific directory-based file structure. Essentially, the app would create a root directory where the user chooses in iCloud Drive, then it would populate user generated files in various levels of nested directories. I have been attempting to use NSMetadataQuery with various predicates and search scopes but haven't been able to get it to directly monitor changes to files or directories that are not in the root directory. Instead, it only monitors files or directories in the root directory, and any changes in a subdirectory are considered an update to the direct children of the root directory. Example iCloud Drive Documents (Not app's ubiquity container) User Created Root Directory (Being monitored) File A Directory A File B An insertion or deletion within Directory A would only return a notification with userInfo containing data for NSMetadataQueryUpdateChangedItemsKey relating to Directory A, and not the file or directory itself that was inserted or deleted. (Query results array also only contain the direct children.) I have tried all combinations of these search scopes and predicates with no luck: query.searchScopes = [ rootDirectoryURL, NSMetadataQueryUbiquitousDocumentsScope, NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope, ] NSPredicate(value: true) NSPredicate(format: "%K LIKE '*.md'", NSMetadataItemFSNameKey) NSPredicate(format: "%K BEGINSWITH %@", NSMetadataItemPathKey, url.path(percentEncoded: false)) I do see these warnings in the console upon starting my query: [CRIT] UNREACHABLE: failed to get container URL for com.apple.CloudDocs [ERROR] couldn't fetch remote operation IDs: NSError: Cocoa 257 "The file couldn’t be opened because you don’t have permission to view it." "Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)"" But I am not sure what to make of that, since it does act normally for finding updates in the root directory. Hopefully this isn't a limitation of the API, as the only alternative I could think of would be to have multiple queries running for each nested directory that I needed updates for.
0
0
76
May ’25
macOS SwiftData app never syncs with CloudKit
I'm using SwiftData with CloutKit with a very simple app. Data syncs between iOS, iPadOS, and visionOS, but not macOS. From what I can tell, macOS is never getting CK messages unless I'm running the app from Xcode. I can listen for the CK messages and show a line in a debug overlay. This works perfectly when I run from Xcode. I can see the notifications and see updates in my app. However, if I just launch the app outside of Xcode I will never see any changes or notifications. It is as if the Mac app never even tries to contact CloudKit. Schema has been deployed in the CloudKit console. The app is based on the multi-platform Xcode template. Again, only the macOS version has this issue. Is there some extra permission or setting I need to set up in order to use CloudKit on macOS? @State private var publisher = NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification).receive(on: DispatchQueue.main) .onReceive(publisher) { notification in // Listen for changes in CK events if let userInfo = notification.userInfo, let event = userInfo[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event { let message = "CloudKit Sync: \(event.type.rawValue) - \(event.succeeded ? "Success" : "Failed") - \(event.description)" // Store for UI display syncNotifications.append(message) if syncNotifications.count > 10 { syncNotifications.removeFirst() } } } .overlay(alignment: .topTrailing) { if !syncNotifications.isEmpty { VStack(alignment: .leading) { ForEach(syncNotifications, id: \.self) { notification in Text(notification) .padding(8) } } .frame(width: 800, height: 500) .cornerRadius(8) .background(Color.secondary.opacity(0.2)) .padding() .transition(.move(edge: .top)) } }
1
0
97
May ’25
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
56
May ’25
What xattrs does iCloud maintain?
As of 2025-05-03, when a macOS user enables iCloud Drive synchronization for Desktop &amp; Documents in US region, does iCloud filter xattrs upon upload or later when downloading back to another macOS host? Or is it the case that iCloud has no filtering of third-party xattrs? Where can I find the technical document outlining exactly what iCloud does with xattrs set on macOS host files and folders synchronized with iCloud Drive?
1
0
77
May ’25
SwiftData crash when using a @Query sort descriptor with a relationship
I am using SwiftData for storage and have a view that uses the @Query property wrapper with a sort descriptor that points to a relationship on a model. In a release build on device running iOS 18.3, the app crashes. This is the line that crashes: @Query(sort: \Item.info.endDate, order: .reverse) private var items: [Item] Item has a relationship to ItemInfo, which is where the endDate property is defined. This code works in debug and on a simulator. In the project referenced here: https://github.com/lepolt/swiftdata-crash, change the scheme build configuration to “Release” and run on device. The app will crash. Using Xcode Version 16.2 (16C5032a) iPhone 12, iOS 18.3 (22D60)
6
11
1.2k
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
Will transferring app affect iCloud's Documents folder access?
My app uses iCloud to let users sync their files via their private iCloud Drive, which does not use CloudKit. FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appending(component: "Documents") I plan to transfer my app to another developer account, but I'm afraid it will affect the access of the app to the existing files in that folder. Apple documentation doesn't mention this case. Has anyone done this before and can confirm if the app will continue to work normally after transferring? Thanks
0
0
32
May ’25
SwiftData shared across apps?
The stuff I've found by searching has confused me, so hopefully someone can help simplify it for me? I have an app (I use it for logging which books I've given away), and I could either add a bunch of things to the app, or I could have another app (possibly a CLI tool) to generate some reports I'd like.
0
0
42
May ’25
CoreData w/ Private and Shared Configurations
I have a CoreData model with two configuration - but several problems. Notably the viewContext only shows data from the .private configuration. Here is the setup: The private configuration holds entities, for example, User and Course and the shared one holds entities, for example, Player and League. I setup the NSPersistentStoreDescriptions to use the same container but with a databaseScope of .private/.shared and with the configuration of "Private"/"Shared". loadPersistentStores() does not report an error. If I try container.initializeCloudKitSchema() only the .private configuration produces CKRecord types. If I create a companion app using one configuration (w/ all entities) the schema initialization creates all CKRecord types AND I can populate some data in the .private and a created CKShare. I see that data in the CloudKit dashboard. If I axe the companion app and run the real thing w/ two configurations, the viewContext only has the .private data. Why? If when querying history I use NSPersistentHistoryTransaction.fetchRequest I get a nil return when using two configurations (but non-nil when using one).
0
0
46
Apr ’25
Suspicious CloudKit Telemetry Data
Starting 20th March 2025, I see an increase in bandwidth and latency for one of my CloudKit projects. I'm using NSPersistentCloudKitContainer to synchronise my data. I haven't changed any CloudKit scheme during that time but shipped an update. Since then, I reverted some changes from that update, which could have led to changes in the sync behaviour. Is anyone else seeing any issues? I would love to file a DTS and use one of my credits for that, but unfortunately, I can't because I cannot reproduce it with a demo project because I cannot travel back in time and check if it also has an increase in metrics during that time. Maybe an Apple engineer can green-light me filing a DTS request, please.
0
1
84
Apr ’25
"Failed to set up CloudKit integration" in TestFlight build
I'm building a macOS + iOS SwiftUI app using Xcode 14.1b3 on a Mac running macOS 13.b11. The app uses Core Data + CloudKit. With development builds, CloudKit integration works on the Mac app and the iOS app. Existing records are fetched from iCloud, and new records are uploaded to iCloud. Everybody's happy. With TestFlight builds, the iOS app has no problems. But CloudKit integration isn't working in the Mac app at all. No existing records are fetched, no new records are uploaded. In the Console, I see this message: error: CoreData+CloudKit: Failed to set up CloudKit integration for store: <NSSQLCore: 0x1324079e0> (URL: <local file url>) Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction.} I thought it might be that I was missing the com.apple.security.network.client entitlement, but adding that didn't help. Any suggestions what I might be missing? (It's my first sandboxed Mac app, so it might be really obvious to anyone but me.)
4
1
3.3k
Apr ’25
SwiftData updates in the background are not merged in the main UI context
Hello, SwiftData is not working correctly with Swift Concurrency. And it’s sad after all this time. I personally found a regression. The attached code works perfectly fine on iOS 17.5 but doesn’t work correctly on iOS 18 or iOS 18.1. A model can be updated from the background (Task, Task.detached or ModelActor) and refreshes the UI, but as soon as the same item is updated from the View (fetched via a Query), the next background updates are not reflected anymore in the UI, the UI is not refreshed, the updates are not merged into the main. How to reproduce: Launch the app Tap the plus button in the navigation bar to create a new item Tap on the “Update from Task”, “Update from Detached Task”, “Update from ModelActor” many times Notice the time is updated Tap on the “Update from View” (once or many times) Notice the time is updated Tap again on “Update from Task”, “Update from Detached Task”, “Update from ModelActor” many times Notice that the time is not update anymore Am I doing something wrong? Or is this a bug in iOS 18/18.1? Many other posts talk about issues where updates from background thread are not merged into the main thread. I don’t know if they all are related but it would be nice to have 1/ bug fixed, meaning that if I update an item from a background, it’s reflected in the UI, and 2/ proper documentation on how to use SwiftData with Swift Concurrency (ModelActor). I don’t know if what I’m doing in my buttons is correct or not. Thanks, Axel import SwiftData import SwiftUI @main struct FB_SwiftData_BackgroundApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Item.self) } } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @State private var simpleModelActor: SimpleModelActor! @Query private var items: [Item] var body: some View { NavigationView { VStack { if let firstItem: Item = items.first { Text(firstItem.timestamp, format: Date.FormatStyle(date: .omitted, time: .standard)) .font(.largeTitle) .fontWeight(.heavy) Button("Update from Task") { let modelContainer: ModelContainer = modelContext.container let itemID: Item.ID = firstItem.persistentModelID Task { let context: ModelContext = ModelContext(modelContainer) guard let itemInContext: Item = context.model(for: itemID) as? Item else { return } itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try context.save() } } .buttonStyle(.bordered) Button("Update from Detached Task") { let container: ModelContainer = modelContext.container let itemID: Item.ID = firstItem.persistentModelID Task.detached { let context: ModelContext = ModelContext(container) guard let itemInContext: Item = context.model(for: itemID) as? Item else { return } itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try context.save() } } .buttonStyle(.bordered) Button("Update from ModelActor") { let container: ModelContainer = modelContext.container let persistentModelID: Item.ID = firstItem.persistentModelID Task.detached { let actor: SimpleModelActor = SimpleModelActor(modelContainer: container) await actor.updateItem(identifier: persistentModelID) } } .buttonStyle(.bordered) Button("Update from ModelActor in State") { let container: ModelContainer = modelContext.container let persistentModelID: Item.ID = firstItem.persistentModelID Task.detached { let actor: SimpleModelActor = SimpleModelActor(modelContainer: container) await MainActor.run { simpleModelActor = actor } await actor.updateItem(identifier: persistentModelID) } } .buttonStyle(.bordered) Divider() .padding(.vertical) Button("Update from View") { firstItem.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) } .buttonStyle(.bordered) } else { ContentUnavailableView( "No Data", systemImage: "slash.circle", // 􀕧 description: Text("Tap the plus button in the toolbar") ) } } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } } private func addItem() { modelContext.insert(Item(timestamp: Date.now)) try? modelContext.save() } } @ModelActor final actor SimpleModelActor { var context: String = "" func updateItem(identifier: Item.ID) { guard let item = self[identifier, as: Item.self] else { return } item.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try! modelContext.save() } } @Model final class Item: Identifiable { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } }
1
1
734
Apr ’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
77
Apr ’25